Skip to content

Instantly share code, notes, and snippets.

@73nko
Last active February 19, 2020 13:49
Show Gist options
  • Save 73nko/c199595eb8a8d09e93bd86e0b7999688 to your computer and use it in GitHub Desktop.
Save 73nko/c199595eb8a8d09e93bd86e0b7999688 to your computer and use it in GitHub Desktop.
Some functional functions Based in array& object destructuring
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)
@73nko
Copy link
Author

73nko commented Feb 19, 2020

const qsort = ([head, ...tail]) => !(head === undefined) ? [...qsort(tail.filter(a => a <= head)), ...[head, ...qsort(tail.filter(a => a > head))]] : [];

  • quicksort using just native methods.

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