Last active
February 19, 2020 13:49
-
-
Save 73nko/c199595eb8a8d09e93bd86e0b7999688 to your computer and use it in GitHub Desktop.
Some functional functions Based in array& object destructuring
This file contains 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 map = ([ head, ...tail ], fn) => | |
(head === undefined && !tail.length) ? [] : | |
(tail.length === 0) ? [ fn(head) ] : | |
[ fn(head), ...map(tail, fn) ]; | |
const filter = ([ head, ...tail ], fn) => { | |
const newHead = fn(head) ? [ head ] : []; | |
return tail.length ? [ ...newHead, ...(filter(tail, fn)) ] : newHead; | |
} | |
const reduce = ([ head, ...tail ], fn, initial) => { | |
if(head === undefined && tail.length === 0) return initial; | |
if(!initial) { | |
const [ newHead, ...newTail] = tail; | |
return reduce(newTail, fn, fn(head, newHead)); | |
} | |
return tail.length ? reduce(tail, fn, fn(initial, head)) : fn(initial, head); | |
} | |
const join = ([ head, ...tail ], separator = ',') => { | |
return (head === undefined && !tail.length) ? '' : | |
tail.length ? head + separator + join(tail, separator) : head; | |
} | |
const qsort = ([head, ...tail]) => (head === undefined) ? [] : | |
[...qsort(filter(tail, a => a <= head)), ...[head, ...qsort(filter(tail, a => a > head))]]; | |
const array = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ]; | |
const count = (tally, fruit) => { | |
tally[fruit] = (tally[fruit] || 0) + 1 ; | |
return tally; | |
} | |
const fib = x => x > 2 ? fib(x - 1) + fib(x - 2) : 1 | |
const users = "Alice;alice@company.com;791-555-3931"; | |
const [ name, email, phone ] = users.split(";"); | |
const foo = [9, 10] | |
const mergedArrays = [3, 5, ...foo] | |
qsort(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const qsort = ([head, ...tail]) => !(head === undefined) ? [...qsort(tail.filter(a => a <= head)), ...[head, ...qsort(tail.filter(a => a > head))]] : [];