Last active
February 9, 2025 15:32
-
-
Save queerviolet/8d39e7e52e17e4c0ae23f6edbce8ef0b to your computer and use it in GitHub Desktop.
Lazy
This file contains hidden or 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 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