Created
October 8, 2017 10:55
-
-
Save kylethebaker/a01a9a5b9760250b88dc610a4d4f6301 to your computer and use it in GitHub Desktop.
Code golfing map/reduce/filter
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
//---------------------------------------------------------------------------- | |
// 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