const input = [1, 1]
const map = (children, fc, context) => {
let result = [];
let count = 0;
mapToArray(children, result, function (child) {
return fc.call(context, child, count++);
})
return result;
}
const forEach = (children, fc, context) => {
map(children, function () {
fc.apply(this, arguments);
}, context)
}
const count = (children) => {
let count = 0;
map(children, function () {
count++;
})
return count;
}
const mapToArray = (children, result, fc) => {
let invokeCallback = false;
const type = typeof children;
if (type === 'string' || type === 'boolean' || type === 'number') {
invokeCallback = true;
}
if (invokeCallback) {
let mappedChild = fc(children);
console.log('mappedChild', mappedChild)
if (mappedChild && mappedChild instanceof Array) {
mappedChild.forEach((c, index) => mapToArray(c, result, c => c));
} else {
result && result.push(children);
}
}
if (children instanceof Array) {
children.forEach((c, index) => {
// console.log('---------------------', children)
mapToArray(c, result, fc)
});
}
}
console.log(map(input, (item, index) => {
console.log(index)
return [1, [
[2, [5, 6], 3], 4
]]
}));
console.log(forEach(input, (item, index) => {
console.log(index)
return [1, [
[2, [5, 6], 3], 4
]]
}));
console.log('count: ', count(input));
判断数组那里,还有可能是迭代器,原理都一样,就是遍历。
个人感觉, 通过修改回调的方式读起来会绕一些,在每个方法里面去遍历感觉会好一些,但是这样扩展起来好简单。