Last active
July 7, 2020 20:41
-
-
Save ducaale/93bd6d49314ef1383f50be95edca9d6e to your computer and use it in GitHub Desktop.
Using ES6 Proxies to turn methods into pipe friendly functions
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
// .babelrc | |
// {"plugins": [["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }]]} | |
const pipeable = (class_) => new Proxy({}, { | |
get: (target, prop) => ( | |
(prop in class_.prototype) | |
? (...args) => (receiver) => class_.prototype[prop].call(receiver, ...args) | |
: class_[prop].bind(class_) // https://stackoverflow.com/a/30819436/5915221 | |
) | |
}); | |
const Array = pipeable(globalThis.Array) | |
const Promise = pipeable(globalThis.Promise) | |
const main = async () => { | |
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
|> Array.map(n => n * 2) | |
|> Array.filter(n => n > 10) | |
|> tap(rcompose(Array.isArray, console.log)) | |
console.log(x) | |
let data = await ( | |
'ali56' | |
|> getUser | |
|> Promise.then(getPosts) | |
|> Promise.then(Array.map(getMostUpvotedComment)) | |
|> Promise.then(Promise.all) | |
|> Promise.catch(err => console.error(err) || []) | |
) | |
|> sumBy(_ =>_.vote) | |
console.log(data) | |
} | |
// some helpers + functions for simulating promises | |
//--------------------------------------- | |
const delay = (t) => new globalThis.Promise(resolve => setTimeout(resolve, t)) | |
const randInt = (min, max) => Math.random() * (max - min) + min; | |
const tap = fn => value => (fn(value), value) | |
const rcompose = (...fn) => (value) => fn.reduce((accum, fn) => fn(accum), value) | |
const sumBy = fn => rcompose(Array.map(fn), Array.reduce((a, b) => a + b)) | |
const getUser = async (username) => { | |
await delay(randInt(600, 1000)) | |
return {id: 1, username: 'ali56', email: '[email protected]'} | |
} | |
const getPosts = async (user) => { | |
await delay(randInt(200, 500)); | |
return [ | |
{id: 1, title: 'X considered harmful', body: 'lorem ipsum'}, | |
{id: 2, title: 'You might not need x', body: 'lorem ipsum'}, | |
{id: 3, title: 'Wireless is a trap', body: 'lorem ipsum'} | |
] | |
} | |
const getMostUpvotedComment = async (post) => { | |
await delay(randInt(600, 1000)) | |
const upvotedComments = [ | |
{body: 'hello', vote: 34}, | |
{body: 'world', vote: 89}, | |
{body: 'this is', vote: 12}, | |
{body: 'a wonderful comment', vote: 56} | |
] | |
return upvotedComments[post.id] | |
} | |
//--------------------------------------- | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment