每天学习几个node库 o(^▽^)┛
————————————————————

filled-array github链接: https://github.com/sindresorhus/filled-array

这个库提供了填充数组的方法,原理如下:

当未指定自定义规则填充数组时,使用array.fill的原生方法

如指定了自定义的规则,则执行n次循环,执行自定义的函数输出需要填充的内容

代码如下:

sindresorhuslink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use strict';
module.exports = function (item, n) {
var ret = new Array(n);
var isFn = typeof item === 'function';

if (!isFn && typeof ret.fill === 'function') {
return ret.fill(item);
}

for (var i = 0; i < n; i++) {
ret[i] = isFn ? item(i, n, ret) : item;
}

return ret;
};

map-array github链接: https://github.com/parro-it/map-array

这个库提供了将对象转换为数组的方法

原理利用了map-obj的库组成新的对象(相关方法容后分析)

代码如下:

parro-itlink
1
2
3
4
5
6
7
8
9
10
11
12
13
'use strict';
const map = require('map-obj');

function mapToArray(obj, fn) {
let idx = 0;
const result = map(obj, (key, value) =>
[idx++, fn(key, value)]
);
result.length = idx;
return Array.from(result);
}

module.exports = mapToArray;