Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Last active January 7, 2019 12:38
Show Gist options
  • Save kettanaito/03f2dd714b5d79c7374b7e3a091ac23d to your computer and use it in GitHub Desktop.
Save kettanaito/03f2dd714b5d79c7374b7e3a091ac23d to your computer and use it in GitHub Desktop.
Useful utility functions I've come up with, found or seen during my career.
/**
* Accepts a number and returns an Array filled with numbers
* starting from 1 and up to the given number.
* @example
* arrayWithNumbers(5)
* // [1, 2, 3, 4, 5]
*/
export default function arrayWithNumbers(number) {
return Array(number).fill().map((_, i) => i + 1)
}
function compose(...funcs) {
return funcs.reduce((f, g) => (...args) => f(g(...args)))
}
import * as R from 'ramda'
/**
* Returns the leaves of the given Object.
* @param {Object} object
* @returns {any[]}
* @example
* getObjectLeaves({ a: 2, b: { c: 3 })
* // [2, 3]
*/
const getObjectLeaves = R.when(
R.is(Object),
R.compose(
// note that partial application doesn't seem to work here
(vals) => R.chain(getObjectLeaves, vals),
R.values,
),
)
export default getObjectLeaves
/**
* Interpolates the given string with the given params.
* @param {string} string
* @param {Object} params
* @returns {string}
*
* @example
* interpolate('/user/{userId}/{messageId}', { userId: 5, messageId: 92 })
* // "/user/5/92"
*/
function interpolate(string, params) {
return string.replace(/{(\w+)}/g, (_, paramName) => params[paramName])
}
/**
* Determines the existance of the provided variable.
* @param {any} variable
* @returns {Boolean}
*/
export default function isset(variable) {
return (typeof variable !== 'undefined') && (variable !== null);
}
/**
* Returns a tuple of data and error for the given promise.
* Useful for error handling of promises with async/await.
* @param {Promise} promise
* @returns {Promise}
* @example
* const [data, error] = await to(getProducts())
*/
export default function to(promise) {
return promise
.then((data) => [data])
.catch((error) => [null, error])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment