Skip to content

Instantly share code, notes, and snippets.

@queerviolet
Last active February 9, 2025 15:32
Show Gist options
  • Save queerviolet/8d39e7e52e17e4c0ae23f6edbce8ef0b to your computer and use it in GitHub Desktop.
Save queerviolet/8d39e7e52e17e4c0ae23f6edbce8ef0b to your computer and use it in GitHub Desktop.
Lazy
function lazy(promise) {
return new Proxy(lazy, {
get(target, prop, receiver) {
if (prop === lazy.promise) { return promise }
if (prop === 'catch' || prop === 'then') {
return ((...args) => promise[prop].apply(promise, args))
}
return lazy(promise.then(x => x[prop]))
},
apply(target, thiz, args) {
const self = thiz[lazy.promise]
return lazy(self.then(self => promise.then(method => method.apply(self, args))))
}
})
}
lazy.promise = Symbol()
const fs = require('fs')
function read(file) {
return new Promise((resolve, reject) =>
fs.readFile(file, (err, buf) =>
err && reject(err) || resolve(buf)))
}
lazy(read('lazy.js'))
.map(x => x + 1)
.filter(x => x % 2)
.toString()
.then(text => console.log(text))
.catch(err => console.error(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment