Created
May 29, 2019 05:48
-
-
Save khpatel4991/709fc7776bf22e9b3cc2017f34e937ef to your computer and use it in GitHub Desktop.
Sample Execution of Transducers
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
const ELEMENTS = 1000000; | |
const add10 = (a: number) => a + 10; | |
const isEven = (a: number) => a % 2 === 0; | |
const getInitial = (): number[] => []; | |
const combine = (acc: number[], elem: number) => (acc.push(elem), acc); | |
const compose = (...fns: Function[]) => (x: number) => fns.reduceRight<number>((acc, fn) => fn(acc), x); | |
const ip = Array.from(Array(ELEMENTS), (_, i) => i); | |
const add20AndFilterEven = compose( | |
add10, | |
add10, | |
isEven | |
); | |
console.time('simple'); | |
ip.map(add10) | |
.map(add10) | |
.filter(isEven); | |
console.timeEnd('simple'); | |
console.time('composed'); | |
ip.map(add20AndFilterEven); | |
console.timeEnd('composed'); | |
const map = (mapFn: (a: number) => number) => (combine: (acc: number[], elem: number) => number[]) => (acc: number[], elem: number) => combine(acc, mapFn(elem)); | |
const filter = (predicateFn: (a: number) => boolean) => (combine: (acc: number[], elem: number) => number[]) => (acc: number[], elem: number) => (predicateFn(elem) ? combine(acc, elem) : acc); | |
const xduce = (xform: Function, combine: (acc: number[], elem: number) => number[], getInitial: () => number[]) => (inputArr: number[]) => inputArr.reduce(xform(combine), getInitial()); | |
const xform = compose( | |
map(add10), | |
map(add10), | |
filter(isEven) | |
); | |
const transform = xduce(xform, combine, getInitial); | |
console.time('mapWithRf'); | |
transform(ip); | |
console.timeEnd('mapWithRf'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For 1M entries time take is as follows:
simple: 221.453ms
composed: 138.141ms
mapWithRf: 41.848ms