Skip to content

Instantly share code, notes, and snippets.

// Named parameters
// Instead this:
articles(ids, published, orderBy, order)
articles([1, 4, 6], true, 'created_at', 'DESC')
// Do this:
articles({ ids, published, orderBy, order })
articles({ ids: [1, 4,6 ], published: true, orderBy: 'created_at', order: 'ASC'})
// Redirect to...
const redirect = (url, replace = false) => {
if (replace) {
return window.location.replace(url);
}
window.location.href = url;
};
redirect('https://overment.com');
// Redirect to...
const redirect = (url, replace = false) => {
if (asLink) {
window.location.href = url;
} else {
window.location.replace(url);
}
};
redirect('https://overment.com');
// Focused tab
const isBrowserTabFocused = () => !document.hidden;
isBrowserTabFocused();
// Redirect to...
const redirect = (url, replace = false) => {
if (asLink) {
window.location.href = url;
}
// Uppercase first letter of a string
function capitalize(str = '') {
return str ? str.charAt(0).toUpperCase() + str.substring(1) : '';
}
// CSV to JSON
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
// Rename object keys
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] },
}),
{}
);
// Object to Query String
const obj = { foo: 'bar', baz: 'qux' }
const queryString = new URLSearchParams(obj).toString()
// foo=bar&baz=qux
// Pipe function composition
const pipeAsyncFunctions = (...fns) => (input) => fns.reduce((chain, func) => chain.then(func), Promise.resolve(input));
// Usage
pipeAsyncFunctions(fn1, fn2)(input).then(result => console.log(result));
// Get URL params
const getParameters = () =>
window.location.search
.slice(1)
.url.split('&')
.reduce(function _reduce(/*Object*/ obj, /*String*/ str) {
str = str.split('=');
obj[str[0]] = decodeURIComponent(str[1]);
return obj;
}, {});