Skip to content

Instantly share code, notes, and snippets.

@dance2die
Created June 15, 2019 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/8f5034246c6ddc302830ecea0b94e640 to your computer and use it in GitHub Desktop.
Save dance2die/8f5034246c6ddc302830ecea0b94e640 to your computer and use it in GitHub Desktop.
Based off of Nicolas's answer - https://dev.to/minimumviableperson/comment/c0b9
// refer to https://dev.to/minimumviableperson/comment/c0b9
// by @minimumviableperson
const double = x => x*2;
const addOne = x => x+1;
const addFn = (...args) => {
let count = 0;
const map = {
'function': (acc, arg) => arg(acc),
'number': (acc, arg) => arg + acc,
}
const apply = (acc, arg) => map[typeof arg](acc, arg) || acc;
const applyArgs = args => args.reduce(apply, count);
const adder = (...args) => args[0] === undefined
? count
: (count = applyArgs(args), adder);
adder.valueOf = () => count;
return adder(...args);
}
// const addFn = (...args) => {
// let count = 0;
// const applyArgs = args => args.reduce((acc, arg) => {
// switch (typeof arg) {
// case 'function': return arg(acc);
// case 'number': return arg + acc;
// default: return acc;
// }
// }, count);
// const adder = (...args) => args[0] === undefined
// ? count
// : (count = applyArgs(args), adder);
// adder.valueOf = () => count;
// return adder(...args);
// }
// const addFn = (...args) => {
// let count = 0;
// const applyArgs = args => args.reduce((acc, arg) => {
// switch (typeof arg) {
// case 'function': return arg(acc);
// case 'number': return arg + acc;
// default: return acc;
// }
// }, count);
// const adder = (...args) => {
// if (args[0] === undefined) return count;
// count = applyArgs(args);
// return adder;
// }
// adder.valueOf = () => count;
// return adder(...args);
// }
@dance2die
Copy link
Author

A deliberate practice to understand currying and spread/rest operators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment