Last active
December 7, 2017 14:55
-
-
Save swissmanu/7a9a90079945e2df6427cb039ceddcc6 to your computer and use it in GitHub Desktop.
Array juggling in JavaScript with functional programming approach
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
// precondition: xs is always an array | |
function head(xs) { | |
if (xs.length === 0) return null | |
return xs[0] | |
} | |
function tail(xs) { | |
return xs.slice(1) | |
} | |
function map(xs, f) { | |
const h = head(xs) | |
if (h !== null) return [f(h), ...map(tail(xs), f)] // tail recursion | |
return xs | |
} | |
function filter(xs, p) { | |
const h = head(xs) | |
if (h !== null) { | |
if (p(h)) return [h, ...filter(tail(xs), p)] | |
return [...filter(tail(xs), p)] | |
} | |
return xs | |
} | |
console.log(map([1,2], x => x * 2)) // [2,4] | |
console.log(filter([-1,0,1,2], x => x > 0)) // [1,2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment