-
-
Save mfrancois3k/1455abb9c67df68dead124c40cd3da0e to your computer and use it in GitHub Desktop.
javascript functional array processing
This file contains hidden or 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
// sml-list-style array functions | |
copy = (xs) => xs.slice(0, xs.length) | |
cons = (x, xs) => { ys = copy(xs); ys.unshift(x); return ys} | |
isEmpty = (xs) => xs.length == 0 | |
hd = (xs) => xs[0] | |
tl = (xs) => { ys = copy(xs); ys.unshift(); return ys } | |
repeat = (n, x) => new Array(n).fill(x) | |
// | |
// create arrays | |
// | |
// create empty array | |
empty = [] | |
// create an array with five 0s | |
five_zeros = repeat(5, 0) // ==> [0, 0, 0, 0, 0] | |
// | |
// map | |
// | |
// `transform` every element | |
// | |
// for example: | |
ins = [1, 2, 3, 4] | |
transform = (x) => x + 1 | |
// imperative version | |
for (i = 0, outs = []; i < ins.length; i++) { | |
outs.push(transform(ins[i])) | |
} | |
// functional version | |
outs = ins.map(x => transform(x)) | |
// example: multiply every element by three | |
mul3 = (xs) => xs.map(x => x * 3) | |
zs = mul3(ins) | |
// | |
// filter | |
// | |
// keep elements if they pass a `test`, discard the others | |
// | |
ins = [1, 2, 3, 4] | |
test = (x) => x > 0 | |
// imperative | |
for (i = 0, outs = []; i < ins.length; i++) { | |
if (test(ins[i])) { | |
outs.push(ins[i]) | |
} | |
} | |
// functional | |
outs = ins.filter(x => test(x)) | |
// example: keep even numbers | |
keepEven = (xs) => ins.filter(x => x % 2 == 0) | |
zs = keepEven([4, 5, 6]) // ==> [4, 6] | |
// | |
// reduce | |
// | |
// `combine` elements, two at a time | |
// | |
ins = [1, 2, 3, 4] | |
combine = (a, x) => null | |
// imperative | |
out = 0 | |
for (i = 0; i < ins.length; i++) { | |
out = combine(out, ins[i]) | |
} | |
// functional | |
out = ins.reduce((a, x) => combine(a, x)) | |
// example : sum of list | |
sum = (xs) => xs.reduce((a, x) => a + x, 0) | |
z = sum([1, 2, 3]) // ==> 6 | |
// example : list of partial sums | |
partials = (xs) => xs.reduce((ys, x) => cons(x, ys), []) | |
zs = partials([2, 5, 5]) // ==> [2, 7, 12] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment