Last active
September 11, 2020 11:37
-
-
Save iboss-ptk/48fd4168abadc012af50d50509688f84 to your computer and use it in GitHub Desktop.
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
// === lib === | |
type Contextualized<C, R> = (context: C) => R | |
const contexualize = contextConsumerGenerator => context => { | |
const generator = contextConsumerGenerator() | |
let contextConsumerIter = generator.next() | |
let consume: any = contextConsumerIter.value | |
while (!contextConsumerIter.done) { | |
contextConsumerIter = generator.next(consume(context)) | |
consume = contextConsumerIter.value | |
} | |
return consume | |
} | |
const get = <Context extends { [key: string]: Value }, Value>(key: keyof Context) => | |
(context: Context): Value => context[key] | |
// =========== | |
type Context = { | |
username: string, | |
age: number | |
} | |
const fancyUserName = contexualize( | |
function*() { | |
const username = yield get('username') | |
return `<<= ${username.toUpperCase()} =>>` | |
} | |
) | |
// === can also be written like this === | |
// ------------------------------------- | |
// | |
// const fancyUserName: Contextualized<{ username: string }, string> = | |
// ({ username }) => `<<= ${username.toUpperCase()} =>>` | |
// | |
// ------------------------------------- | |
const friendsWithSameAgeRange = (margin: number) => contexualize( | |
function*() { | |
const users = [ | |
{ username: 'boz', age: 12 }, | |
{ username: 'biz', age: 13 }, | |
{ username: 'buz', age: 14 }, | |
] | |
const currentUserAge = yield get('age') | |
return users.filter(({ age }) => (age >= currentUserAge - margin && age <= currentUserAge + margin)) | |
} | |
) | |
const fancyNameWithFriends = contexualize( | |
function* () { | |
const funame = yield fancyUserName | |
const friends = yield friendsWithSameAgeRange(1) | |
return `${funame} :: ${friends.map(f => f.username)}` | |
} | |
) | |
const context = { username: 'iboss', age: 12 } | |
// inject context at top level | |
console.log(fancyNameWithFriends(context)) // <<= IBOSS =>> :: boz,biz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment