Created
November 18, 2017 18:55
-
-
Save liorean/58667acd9b8b4554a9c7b4740065e93c to your computer and use it in GitHub Desktop.
Desugared map from https://blog.benestudio.co/pattern-matching-in-javascript-es6-10fff60aae79
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
//Original: | |
// | |
//const map = (f, [x, …xs]) => ( | |
// (x === undefined && xs.length === 0) ? [] | |
// : [f(x), …map(f, xs)] | |
//); | |
const map=(f,array)=>{ | |
const iterator=array[Symbol.iterator]() | |
let {done,value}=iterator.next() | |
let x=value | |
let xs=[] | |
;({done,value}=iterator.next()) | |
while(!done){ | |
xs[xs.length]=value | |
;({done,value}=iterator.next())} | |
if('return' in iterator) | |
iterator.return() | |
return (x===undefined && xs.length===0) | |
?[] | |
:[f(x),...map(f, xs)]} | |
console.log(map(e=>2**e,[0,1,2,3,4,5,6,7,8,9])) | |
//Testing in the EcmaScript shells I have installed: | |
//> ch desugaredmap.es | |
// 1,2,4,8,16,32,64,128,256,512 | |
//> js desugaredmap.es | |
// 1,2,4,8,16,32,64,128,256,512 | |
//> node desugaredmap.es | |
// [ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment