这是由@theprtk提供的代码更新版本。为了展示一般化版本并提供一个例子,它已经进行了一些清理。
注意:我想在他的帖子下留言,但我还没有足够的声望。
const transduce = {
map: changeInput => reducing => (acc, input) =>
reducing(acc, changeInput(input)),
filter: predicate => reducing => (acc, input) =>
predicate(input) ? reducing(acc, input) : acc,
compose: (...args) => x => {
const fns = args;
var i = fns.length;
while (i--) x = fns[i].call(this, x);
return x;
},
};
const example = {
data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
concat: (acc, input) => acc.concat([input]),
getSrc: x => x.src,
filterJson: x => x.src.split('.').pop() !== 'json',
};
const reduceFn = example.concat;
const mapFn = transduce.map(example.getSrc);
const filterFn = transduce.filter(example.filterJson);
const composeFn = transduce.compose(
filterFn,
mapFn,
transduce.map(x => x.toUpperCase() + '!'),
);
const exampleFns = {
transducers: [
mapFn(reduceFn),
filterFn(mapFn(reduceFn)),
composeFn(reduceFn),
],
raw: [
(acc, x) => acc.concat([x.src]),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
],
};
const execExample = (currentValue, index) =>
console.log('Example ' + index, example.data.reduce(currentValue, []));
exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);
img.src
? - GrayedFoxundefined
将被放入数组中,而不是null
。并没有更好... - FZs