Last active
March 6, 2023 06:54
-
-
Save nagyadam2092/595d2da4624209e22e5f13bef0a36596 to your computer and use it in GitHub Desktop.
JavaScript infinite streams
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
const stream = (value, next = null) => ({ | |
map: function(f) { | |
return stream(f(value), next ? next.map(f) : null) | |
}, | |
filter: function(pred) { | |
if (pred(value)) { | |
return stream(value, next ? next.filter(pred) : null) | |
} else { | |
return next ? next.filter(pred) : emptyStream | |
} | |
}, | |
value, | |
next | |
}) | |
const emptyStream = { | |
map: function() { | |
return this | |
}, | |
filter: function() { | |
return this | |
} | |
} | |
const stream1 = stream(1, stream(2, stream(3, emptyStream))) | |
const mappedStream = stream1.map(x => x.toString()) | |
const filteredStream = stream1.filter(x => x > 1) | |
console.log(mappedStream) // { value: '1', next: {...}, map: [Function], next: { map: [Function], next: { map: [Function], next: [Object] } } } | |
console.log(filteredStream) // { value: 2, next: {...}, map: [Function], next: { map: [Function], next: [Object] } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment