Skip to content

Instantly share code, notes, and snippets.

@iOnline247
Last active September 22, 2021 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iOnline247/d6cba10aa752a27c0efe8764a3559cad to your computer and use it in GitHub Desktop.
Save iOnline247/d6cba10aa752a27c0efe8764a3559cad to your computer and use it in GitHub Desktop.
JavaScript Utilities and Example Usage
/*
* Helpful JS utils & example usage.
*/
const prop = (k) => (o) => o[k];
const props = (ks) => (o) => ks.map((k) => o[k]);
const map = (f) => (a) => a.map(f);
const filter = (f) => (a) => a.filter(f);
const split = (delim) => (s) => {
s = String(s);
return s.split(delim);
};
const join = (sep) => (a) => a.join(sep);
const uniq = (a) => Array.from(new Set(a));
const pipe =
(...fns) =>
(x) =>
fns.reduce((v, f) => f(v), x);
const asyncPipe =
(...fns) =>
(x) =>
fns.reduce(async (y, f) => f(await y), x);
// const chainPromises = (funcs) => {
// return () =>
// funcs.reduce((chain, func) => {
// return chain.then((chainResults) => {
// let exec = func();
// // https://gist.github.com/akhoury/622acbe3bb4c29412657e964ac9af7ea
// const isPromise = exec && typeof exec.then === "function";
// if (!isPromise) {
// exec = Promise.resolve(exec);
// }
// return exec.then(Array.prototype.concat.bind(chainResults));
// });
// }, Promise.resolve([]));
// };
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#running_promises_in_sequence
// See asyncPipe above for brevity.
const runPromiseInSequence = (arr, input) => {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input)
);
};
const parseBoolean = (() => {
const boolTransform = {
0: false,
F: false,
N: false,
NO: false,
FALSE: false,
1: true,
ON: true,
T: true,
Y: true,
YES: true,
TRUE: true,
};
return (v) => !!boolTransform[`${v}`.trim().toUpperCase()];
})();
const chunk = (size) => (arr) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_v, i) => arr.slice(i * size, i * size + size));
// Example code.
/*
* `prop` example
* Gets property from an object
*/
/*
const item = {AuthorId: 2, Title: 'Hola, mundo'};
const getTitle = prop('Title');
const title = getTitle(item);
*/
/*
* `props` example
* Gets properties from an object
*/
/*
const item = {AuthorId: 2, Title: 'Hola, mundo', DueDate: 1511466836278};
const getItemInfo = props(['AuthorId', 'Title']);
const itemInfo = getItemInfo(item);
*/
/*
* `map` example
* Easily provide descriptive names to your mapping of arrays.
*/
/*
const data = [13, 26, '35555', function(){}, {}, [], 1, 2, 3, 4, 5];
const isEven = map(function(v) {
if (Number.isInteger(v)) {
return v % 2 === 0;
} else {
return 'Not a number';
}
});
const results = isEven(data);
console.log(results);
*/
/*
* `filter` example
* Easily provide descriptive names to your filtering of arrays.
*/
/*
const data = [13, 26, '35555', function(){}, {}, [], 1, 2, 3, 4, 5];
const isNumber = filter(function(v) {
if (Number.isInteger(v)) {
return v;
}
});
const results = isNumber(data);
console.log(results);
*/
/*
* `split` example
* Creates an array from a string using the delimiter passed in.
*/
/*
const text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
const splitOnComma = split(',');
const results = splitOnComma(text);
console.log(results);
*/
/*
* `join` example
* Creates a string from an array using the separator passed in.
*/
/*
const arrOfStrings = ['Lorem ipsum dolor sit amet', 'consectetuer adipiscing elit.'];
const joinWithComma = join(',');
const results = joinWithComma(arrOfStrings);
console.log(results);
*/
/*
* `uniq` example
* Creates an array with unique values (shallow).
*/
/*
const arr = [1,2,3,1,1,2,3,4,5];
const results = uniq(arr);
console.log(results);
*/
/*
* `pipe` example
* Creates array from a string, reverses the array, then joins it back into a string.
*/
/*
const reverseArray = arr => arr.reverse();
const reverseString = pipe([split(''), reverseArray, join('')]);
const output = reverseString('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.');
console.log(output);
*/
/*
* `asyncPipe example
* Sequentially resolves promises from an array.
*/
/*
const f = n => Promise.resolve(n + 1);
const g = n => Promise.resolve(n * 2);
const h = asyncPipe(f, g);
h(20).then(console.log);
*/
/*
function getData(callNumber, time) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
const rando = Math.random();
if (rando > 0.99) {
reject(callNumber);
} else {
resolve(callNumber);
}
}, time);
});
}
function get1() {
return 1;
}
console.time('PromiseChain');
const getAllData = asyncPipe([
get1,
getData.bind(null, 15, 1000),
// () => 1,
get1,
getData.bind(null, 25, 3000),
get1,
getData.bind(null, 15, 500)
]);
// Note the time... The promises within getAllData are at work
// while this setTimeout is waiting to be executed. These are Thunks @ work.
setTimeout(() => {
getAllData().then(function ([...args]) {
const total = args.reduce((acc, curr) => acc + curr, 0);
console.log(total);
console.timeEnd('PromiseChain');
});
}, 10000);
*/
// Mock AJAX call.
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function getData() {
const items = await resolveAfter2Seconds([
{
Col1: 1,
Col2: 2,
},
{
Col1: 3,
Col2: 4,
},
]);
return items;
}
getData().then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment