Skip to content

Instantly share code, notes, and snippets.

@kombuchamp
Created January 19, 2021 14:26
Show Gist options
  • Save kombuchamp/9ae498100d5547e635df4ba806e392fd to your computer and use it in GitHub Desktop.
Save kombuchamp/9ae498100d5547e635df4ba806e392fd to your computer and use it in GitHub Desktop.
Array methods ponyfills UX utilities
// Assume we have ponyfilled versions of array methods
const map = (arr, cb) => [].map.call(arr, cb);
const reduce = (arr, cb) => [].reduce.call(arr, cb);
// What we wanna do without ponyfills
const res = [1,2,3]
.map(x => x * 10)
.reduce((cur, prev) => cur + prev);
// What we can do with ponyfills
const foo = map([1,2,3], x => x * 10);
const res1 = reduce(foo, (cur, prev) => cur + prev);
/**
* Pipe utility function
* Allows for piping array functions in more declarative way
*/
const pipe = funcs => initialValue => {
let value = initialValue;
funcs.forEach(([fn, ...additionalArgs]) => {
value = fn(value, ...additionalArgs);
});
return value;
}
const res2 = pipe([
[map, x => x * 10],
[reduce, (cur, prev) => cur + prev]
])([1,2,3]);
console.assert(res1 === res2)
/**
* IterableArray wrapper
* Allows for chaining almost like with causal array functions
*/
class IterableArray {
constructor(arr) {
this.val = arr;
}
map(cb) {
this.val = map(this.val, cb);
return this;
}
reduce(cb) {
this.val = reduce(this.val, cb);
return this;
}
toValue() {
return this.val;
}
}
const iter = (arr) => new IterableArray(arr);
const res3 = iter([1,2,3])
.map(x => x * 10)
.reduce((cur, prev) => cur + prev)
.toValue();
console.assert(res1 === res3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment