Created
September 1, 2022 16:28
-
-
Save Sandarr95/f5cac5b635b26bd85c2256eb9b1d2dc4 to your computer and use it in GitHub Desktop.
Stateless transducer setup by injecting a new transducer each step (no init or completion functions)
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 map(f) { | |
return function(rf) { | |
return function(result, item) { | |
const [new_rf, new_result] = rf(result, f(item)) | |
return [map(f)(new_rf), new_result] | |
} | |
} | |
} | |
function takeNth(n, state = n) { | |
return function(rf) { | |
return function(result, item) { | |
if(n === state) { | |
const [new_rf, new_result] = rf(result, item) | |
return [takeNth(n, 1)(new_rf), new_result] | |
} else { | |
return [takeNth(n, state+1)(rf), result]; | |
} | |
} | |
} | |
} | |
function comp(...fs) { | |
return function(arg) { | |
return fs.reverse().reduce((result, f) => f(result), arg) | |
} | |
} | |
function concat(result = [], item) { | |
return [...result, item] | |
} | |
function stateless_reducer(f) { | |
return function(result, item) { | |
return [stateless_reducer(f), f(result, item)] | |
} | |
} | |
function stateless_reduce(stateless_rf, init, coll) { | |
return coll.reduce( | |
([rf, result], item) => rf(result, item), | |
[stateless_rf, init] | |
)[1]; | |
} | |
const xf = comp( | |
map(i => i + 1), | |
takeNth(5), | |
map(i => i % 7) | |
) | |
const pipe = xf(stateless_reducer(concat)); | |
const countTo1000 = Array.from({ length: 1000 }).map((_, i) => i); | |
const result = stateless_reduce(pipe, [], countTo1000) | |
console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment