Skip to content

Instantly share code, notes, and snippets.

@joergpatz
Last active May 10, 2022 11:46
Show Gist options
  • Save joergpatz/b0dd7ae8589d3d9915ffb657a0dc4309 to your computer and use it in GitHub Desktop.
Save joergpatz/b0dd7ae8589d3d9915ffb657a0dc4309 to your computer and use it in GitHub Desktop.
neat javascript helpers
/**
* A pipe function takes an n sequence of operations
* in which each operation takes an argument process it and gives the processed output as an input for the next operation in the sequence.
* The result of a pipe function is a function that is a bundled up version of the sequence of operations.
*
* const pipe = (op1, op2, op3, ... , opN) => {
* return (arg) => opN(op3(op2(op1(arg))));
* }
*/
const bundle = (a, b) => arg => b(a(arg));
const pipe = (...ops) => ops.reduce(bundle);
/**
* Create an object with a member added conditionally
*/
const obj = {
a: 'ok',
...(false && {b: 'ok'})
};
/**
* Testing the existence of nested object keys by inline it's properties value
*/
const test = (((foo || {}).level1 || {}).level2 || {}).bar;
/**
* streamline async / await error handling, with less try .. catch
*
* resolves the success response to an array with the return data as second item
* and the Error received from the catch as the first.
*
* @param promise
* @returns {Promise}
*/
function to(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
}
[err, data] = await to(promise);
if(err) throw new Error('error occurred');
/**
* cast any primitive data type to Boolean
*
* @param value
* @returns {boolean}
*/
function primitiveToBoolean(value) {
if (value === 'true') {
return true;
}
return typeof value === 'string'
? !!+value // we parse string to number first
: !!value;
}
/**
* Simple is object check.
*
* @param item
* @returns {boolean}
*/
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item) && item !== null);
}
/**
* checks if a string is a Javascript Object Notation (JSON) string
*
* @param item
* @returns {boolean}
*/
function isJsonString(item) {
item = typeof item !== 'string'
? JSON.stringify(item)
: item;
try {
item = JSON.parse(item);
} catch (e) {
return false;
}
return typeof item === 'object' && item !== null;
}
/**
* splits a string and return fields position
*
* @param str
* @param char
* @param pos
* @returns {string}
*/
function splitAndValueOf(str, char, pos = 0) {
if (str && str.includes(char)) {
return str.split(char)[pos];
}
return str;
}
/**
* Replacing switch statements with Object literals
*
* @param type
* @returns {string}
*/
function getDrink(type) {
var drinks = {
'coke': function () {
return 'Coke';
},
'pepsi': function () {
return 'Pepsi';
},
'lemonade': function () {
return 'Lemonade';
},
'default': function () {
return 'Default item';
}
};
return (drinks[type] || drinks['default'])();
}
/**
* Deep merge two objects.
* immutable (does not modify the inputs)
*
* @param target
* @param source
* @returns {Object}
*/
function mergeDeep(target, source) {
const output = Object.assign({}, target);
if (isObject(target) && isObject(source)) {
Object.keys(source).forEach(key => {
if (isObject(source[ key ])) {
if (!(key in target)) {
Object.assign(output, { [ key ]: source[ key ] });
} else {
output[ key ] = mergeDeep(target[ key ], source[ key ]);
}
} else {
Object.assign(output, { [ key ]: source[ key ] });
}
});
}
return output;
}
/**
* join & encode url params from an object
*
* @param paramObject
* @returns {string}
*/
function buildUrlQueryParams(paramObject) {
const buffer = [];
Object.entries(paramObject)
.filter(([key, value]) => key && value)
.forEach(([key, value]) => {
buffer.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return buffer.join('&');
}
/**
* Build nested collection out of a flat collection with parent_id related properties
*
* @param data
* @param parent_id
* @returns {Array}
*/
function getNestedChildren(data, parent_id = null) {
const nested = [];
for (const item of data) {
if (item.parent_id === parent_id) {
const children = getNestedChildren(data, item.id);
if (children.length) {
item.children = children;
}
nested.push(item);
}
}
return nested;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment