Skip to content

Instantly share code, notes, and snippets.

@nagyadam2092
Last active March 6, 2023 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagyadam2092/595d2da4624209e22e5f13bef0a36596 to your computer and use it in GitHub Desktop.
Save nagyadam2092/595d2da4624209e22e5f13bef0a36596 to your computer and use it in GitHub Desktop.
JavaScript infinite streams
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