const count = (func) => {
let count = 0;
return [
(...args) => {
count++;
func(...args);
},
() => {
console.log(`执行了${count}次`);
},
];
};
const [add, getCount] = count(() => console.log("add"));
add();
add();
add();
add();
add();
add();
add();
add();
getCount();
const conveyorFunc = (...func) => {
return func.reduce(
(prev, cur) => {
return (input) => {
return cur(prev(input));
};
},
(input) => input
);
};
const conveyorModel = conveyorFunc(
(input) => input + 5,
(input) => input - 3,
(input) => input + 10,
(input) => input + 2,
(input) => input * 3,
(input) => input / 2
);
console.log(conveyorModel(1));
const curyFunc = (func, args = []) => {
return (input) => {
const newArgs = args.concat(input);
if (newArgs.length >= func.length) {
return func(...newArgs);
} else {
return curyFunc(func, newArgs);
}
};
};
const add = (a, b, c, d) => a + b + c + d;
const curyAdd = curyFunc(add);
console.log(curyAdd(1)(2)(3)(4));
const pipe =
(...fns) =>
(x) =>
fns.reduce((v, f) => f(v), x);
const compose =
(...fns) =>
(x) =>
fns.reduceRight((v, f) => f(v), x);
const add = (x) => x + 1;
const multiply = (x) => x * 2;
const subtract = (x) => x - 3;
const divide = (x) => x / 4;
const addThenMultiply = pipe(add, multiply);
const subtractThenDivide = compose(subtract, divide);
console.log(addThenMultiply(1));
console.log(subtractThenDivide(1));