Skip to content

Instantly share code, notes, and snippets.

@kylethebaker
Created October 8, 2017 10:55
Show Gist options
  • Save kylethebaker/a01a9a5b9760250b88dc610a4d4f6301 to your computer and use it in GitHub Desktop.
Save kylethebaker/a01a9a5b9760250b88dc610a4d4f6301 to your computer and use it in GitHub Desktop.
Code golfing map/reduce/filter
//----------------------------------------------------------------------------
// recursive golfed reduce
//----------------------------------------------------------------------------
let r = (f, a, [h, ...t]) => !t.length ? f(a, h) : r(f, f(a, h), t)
function reduce(fn, acc, [x, ...xs]) {
return !xs.length
? fn(acc, x)
: reduce(fn, fn(acc, x), xs);
}
//----------------------------------------------------------------------------
// recursive golfed map
//----------------------------------------------------------------------------
let m = (f, [h, ...t]) => !t.length ? [f(h)] : [f(h), ...m(f, t)]
function map(fn, [x, ...xs]) {
return !xs.length
? [fn(x)]
: [fn(x), ...map(fn, xs)]
}
//----------------------------------------------------------------------------
// recursive golfed map built using reduce
//----------------------------------------------------------------------------
let m2 = (f, xs) => r((ys, y) => [...ys, f(y)], [], xs);
function map_from_reduce(fn, xs) {
let reduce_fn = (results, x) => [...results, fn(x)];
return reduce(reduce_fn, [], xs);
}
//----------------------------------------------------------------------------
// recursive golfed filter
//----------------------------------------------------------------------------
let f = (p, [h, ...t]) => !t.length ? p(h) ? [h] : [] : p(h) ? [h, ...f(p, t)] : f(p, t)
function filter(fn, [x, ...xs]) {
return !xs.length
? fn(x) ? [x] : []
: fn(x) ? [x, ...filter(fn, xs)] : filter(fn, xs);
}
//----------------------------------------------------------------------------
// recursive golfed filter built using reduce
//----------------------------------------------------------------------------
let f2 = (p, xs) => r((ys, y) => p(y) ? [...ys, y] : ys, [], xs)
function filter_from_reduce(fn, xs) {
let reduce_fn = (results, x) => fn(x) ? [...results, x] : results
return reduce(reduce_fn, [], xs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment