Last active
July 12, 2016 04:10
-
-
Save efrence/13ec6da93c8b7be6707e08347dbe3716 to your computer and use it in GitHub Desktop.
Lazy comprehention
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
function take(n, str) { | |
function _take(n, str, accum) { | |
if (n === 0) { | |
return accum; | |
} | |
const { value, next } = str(); | |
return _take(n - 1, next, accum.concat(value)); | |
} | |
return _take(n, str, []); | |
} | |
function stream(fn, initial) { | |
function _stream(value) { | |
return { | |
value, | |
next() { | |
return _stream(fn(value)); | |
} | |
}; | |
} | |
return () => _stream(initial); | |
} | |
function smap(fn, originalStr) { | |
function _stream(str) { | |
const { value, next } = str(); | |
return { | |
value: fn(value), | |
next() { | |
return _stream(next); | |
} | |
}; | |
} | |
return () => _stream(originalStr); | |
} | |
function sfilter(fn, originalStr) { | |
function _stream(str) { | |
const { value, next } = str(); | |
if (fn(value)) { | |
return { | |
value, | |
next() { | |
return _stream(next); | |
} | |
}; | |
} | |
return _stream(next); | |
} | |
return () => _stream(originalStr); | |
} | |
function lazyComprehention(map_fn,str,filter_fn){ | |
return smap(map_fn,sfilter(filter_fn,str)); | |
} | |
const nats = stream(n => n + 1, 1); | |
squared_odd_numbers = lazyComprehention(n => n * n, nats, n => n % 2 !== 0) | |
console.log(take(10,squared_odd_numbers)); // [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment