Last active
September 3, 2021 10:23
-
-
Save abuseofnotation/0f26a5f004841326bd410a473c4aadc6 to your computer and use it in GitHub Desktop.
Invokes functions that are given as arguments in succession. Works like flow/pipe/compose, but all functions are given an additional "state" argument which may contain any additional values that are needed by all functions e.g. configuration. Inspired by the Reader monad.
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
// Invokes functions that are given as arguments in succession. | |
// Works like flow/pipe/compose, but all functions are given an additional "state" argument | |
// which may contain any additional values that are needed by all functions e.g. configuration. | |
// Inspired by the Reader monad. | |
const readerCompose = (functions) => functions | |
.reduce((fn1, fn2) => (state) => (...args) => | |
fn2(state)(fn1(state)(...args)) | |
) | |
const state = { | |
stateVal: 5, | |
} | |
const test = readerCompose([ | |
(state) => (val) => { | |
console.log('input is now', val) // 1 | |
console.log('Value in state is', state.stateVal) // 5 | |
console.log('Adding one to input') | |
return val + 1 | |
}, | |
(state) => (val) => { | |
console.log('input is now ', val) // 2 | |
console.log('Value in state is still', state.stateVal) // 5 | |
return val | |
} | |
])({stateVal: 5}) | |
test(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment