-
-
Save dvidsilva/a799098b5b02bac0c9b3 to your computer and use it in GitHub Desktop.
es6 and recursion, examples from http://raganwald.com/2015/02/02/destructuring.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const length = ([first, ...rest]) => | |
first === undefined | |
? 0 | |
: 1 + length(rest); | |
const flatten = ([first, ...rest]) => { | |
if (first === undefined) { | |
return []; | |
} | |
else if (!Array.isArray(first)) { | |
return [first, ...flatten(rest)]; | |
} | |
else { | |
return [...flatten(first), ...flatten(rest)]; | |
} | |
} | |
const squareAll = ([first, ...rest]) => | |
first === undefined | |
? [] | |
: [first * first, ...squareAll(rest)]; | |
const truthyAll = ([first, ...rest]) => | |
first === undefined | |
? [] | |
: [!!first, ...truthyAll(rest)]; | |
const mapWith = (fn, [first, ...rest]) => | |
first === undefined | |
? [] | |
: [fn(first), ...mapWith(fn, rest)]; | |
const foldWith = (fn, terminalValue, [first, ...rest]) => | |
first === undefined | |
? terminalValue | |
: fn(first, foldWith(fn, terminalValue, rest)); | |
foldWith((number, rest) => | |
number * number + rest, 0, [1, 2, 3, 4, 5]) | |
// console.log(mapWith((x) => x * x, [1, 2, 3, 4, 5])); | |
// console.log(mapWith((x) => !!x, [null, true, 25, false, "foo"])); | |
//console.log(squareAll([1, 2, 3, 4, 5])); | |
//console.log(flatten(["foo", [3, 4, []]])); | |
//console.log(length([1,2,3,5])); | |
//console.log(truthyAll([null, true, 25, false, "foo"])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment