Skip to content

Instantly share code, notes, and snippets.

@swissmanu
Last active December 7, 2017 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swissmanu/7a9a90079945e2df6427cb039ceddcc6 to your computer and use it in GitHub Desktop.
Save swissmanu/7a9a90079945e2df6427cb039ceddcc6 to your computer and use it in GitHub Desktop.
Array juggling in JavaScript with functional programming approach
// 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