Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active February 15, 2017 10:24
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 gvergnaud/4f672ff80222eb2066b3c771992e61dc to your computer and use it in GitHub Desktop.
Save gvergnaud/4f672ff80222eb2066b3c771992e61dc to your computer and use it in GitHub Desktop.
/* --------------------------------------------------------------------------- *
Utilities for managing lists, implemented using only recursion
* --------------------------------------------------------------------------- */
const head = ([x]) => x
const tail = ([x, ...rest]) => rest
const last = xs => xs[xs.length - 1]
const length = xs => xs.length
const drop = (n, xs) => n ? drop(n - 1, tail(xs)) : xs
const take = (n, [x, ...rest]) => n ? [x, ...take(n - 1, rest)] : []
const reverse = ([x, ...rest]) => length(rest) ? [...reverse(rest), x] : [x]
const map = (f, [x, ...rest]) => length(rest) ? [f(x), ...map(f, rest)] : [f(x)]
const filter = (f, [x, ...rest]) => length(rest) ? f(x) ? [x, ...filter(f, rest)] : filter(f, rest) : f(x) ? [x] : []
const reduce = (f, acc, [x, ...rest]) => length(rest) ? reduce(f, f(acc, x), rest) : f(acc, x)
const reduceRight = (f, acc, xs) => reduce(f, acc, reverse(xs))
const fact = x => x ? x * fact(x - 1) : 1
const compose = (...funcs) => x => reduceRight((acc, f) => f(acc), x, funcs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment