我希望在方法链的中间看到数组的状态:
arr.filter(...)
.flatMap(...)
.map(...)
.sort() // fyi, sort returns the sorted array
// say I want to see the array content at this point
.map(...)
.slice(0, 10)我可以通过使用underscorejs中的tap()函数来实现这一点,如this answer中所述。但是我想在不使用任何库的情况下做到这一点。
我浏览了一下Array prototype functions,它似乎没有类似于tap函数的功能。有什么解决方法吗?
发布于 2019-03-20 02:50:44
只需自己编写一个:
// Be careful when overriding the default prototype, it might cause other code to fail or is a performance nightmare
Object.defineProperty(Array.prototype, "log", {
enumerable: false, // < make sure it doesnt suddenly appear somewhere (defaults to false though)
value(name) {
console.log(name, this);
return this; // < enable chaining
},
});
[1, 2, 3].filter(it => it > 1).log("after filtering");如果你想自动记录日志,你可以写一个可链接的包装器:
const logChain = (arr) => ({
log() {
console.log(arr);
return this;
},
result() { return arr; },
map(cb, context) {
return logChain(arr.map(cb, context)).log();
},
// filter reduce etc.
});
logChain([1, 2, 3])
.map(it => it + 1) // logs [2, 3, 4]
.result() // unwrap或者,如果您想用最少的代码实现这一点,只需执行以下操作:
const log = (...mutations) => arr => mutations.reduce((prev, op) => (it => (console.log(it), it))(op(prev)), arr);
log(
it => it.map(n => n + 1),
it => it.filter(it => it > 2)
)([1, 2, 3, 4])https://stackoverflow.com/questions/55248000
复制相似问题