Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const reduce = (reducer, initial, arr) => {
- let acc = initial;
- for (let i = 0, { length } = arr; i < length; i++) {
- acc = reducer(acc, arr[i]);
- }
- return acc;
- };
- const addAll = nums => reducer((acc, curr) => acc + curr, 0, nums);
- console.log(addAll([1, 2, 3, 4, 5, 6, 7, 8, 9]));
- const filter = (fn, arr) =>
- reduce((acc, curr) => (fn(curr) ? acc.concat([curr]) : acc), [], arr);
- const over5 = nums => filter(num => num > 5, nums);
- console.log(over5([1, 2, 3, 4, 5, 6, 7, 8, 9]));
- const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
- const trace = label => value => {
- console.log(`${label}: ${value}`);
- return value;
- };
- const g = n => n + 1;
- const f = n => n * 2;
- const h = compose(
- trace('after f'),
- f,
- trace('after g'),
- g
- );
- h(20);
- const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
- const j = pipe(
- g,
- trace('after g'),
- f,
- trace('after f')
- );
- const map = fn => mappable => mappable.map(fn);
- const arr = [1, 2, 3, 4];
- const isEven = n => n % 2 === 0;
- const stripe = n => (isEven(n) ? 'dark' : 'light');
- const stripeAll = map(stripe);
- const striped = stripeAll(arr);
- console.log(striped);
- const flip = fn => a => b => fn(b)(a);
- const traceFlip = value => label => {
- console.log(`${label}: ${value}`);
- return value;
- };
- const flippedCorrectTrace = flip(traceFlip);
- // array.reduce(
- // reducer: (accumulator: Any, current: Any) => Any,
- // initialValue: Any
- // ) => accumulator: Any”
- const map = (fn, arr) =>
- arr.reduce((acc, item, index, arr) => acc.concat(fn(item, index, arr)), []);
- const filter = (fn, arr) =>
- arr.reduce((newArr, item) => (fn(item) ? newArr.concat([item]) : newArr), []);
- // “Partial applications can take as many or as few arguments a time as desired.Curried functions on the other hand always return a unary function: a function which takes one argument.
- // All curried functions return partial applications, but not all partial applications are the result of curried functions.
- // The unary requirement for curried functions is an important feature.”
- // Tiny, recursive autocurry
- const curry = (f, arr = []) => (...args) =>
- (a => (a.length === f.length ? f(...a) : curry(f, a)))([...arr, ...args]);
- const add3 = curry((a, b, c) => a + b + c);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement