Ramda recepies
Here is a list of small functions, easy to apply in different situations and that are not preset in the Ramda core library.
merge-and-apply
Helper function useful for updating the state and then merging the rest of the object.
/**
* Helper function useful for updating the
* state and then merging the rest of the object.
*
* @func
* @param {Object} spec
* @return {Function<Object>}
*/
const applySpecAndMerge = R.curry(spec =>
R.converge(R.merge, [R.identity, R.applySpec(spec)])
)
left-pad
Prepend a left pad to the string, using the amount specified.
/**
* Get the amount of space needed to generate for the left pad.
*
* @param {Number} wantedLength
* @param {String} stringToAppend
* @return {String}
*/
const getAmountOfLeftPad = R.compose(
R.max(0),
(length, str) => R.subtract(length, R.length(str))
)
/**
* Get the left pad of `0`s.
*
* @param {Number} wantedLength
* @param {String} string
* @return {String}
*/
const getLeftPad = R.compose(R.join(''), R.repeat('0'), getAmountOfLeftPad)
/**
* Prepend a left pad to the string, using the amount specified.
*
* @param {Number} wantedLength
* @param {String} string
* @return {String}
*/
const leftPad = R.compose(R.apply(R.concat), R.juxt([getLeftPad, R.nthArg(1)]))
associate-with-origin
Executes the function in the 2nd argument with the value in the 3rd argument, which should return an object and then apply R.assoc
with the name in the 1st argument and the original value.
/**
* Executes the function in the 2nd argument with the value
* in the 3rd argument, which should return an object and then apply
* `R.assoc` with the name in the 1st argument and the original value.
*
* @param {String} name
* @param {Function} fn
* @param {Any} value
* @return {Object}
*/
const assocOrig = R.curry((name, fn, val) => R.assoc(name, val, fn(val)))
conditional-array
Create an array based on a predicate and a value in case of passing.
/**
* Create an array based on a predicate and a value in case of passing.
*
* @example
* conditionalArray([
* [R.T, 'This will always be present in the array'],
* [R.has('myProp'), R.complement(R.multiply(2), R.prop('myProp'))]
* ])
*
* @public
* @func
* @param {Object} spec
* @param {Object} subject
*/
const conditionalArray = R.curry((spec, subject) =>
R.compose(
R.reject(R.equals(false)),
R.map(([predicate, transformer]) => (predicate(subject) ? transformer : false))
)(spec)
)
merge-deep-all
This one isn't mine, I found it in stackoverflow.
const mergeDeepAll = R.unapply(R.reduce(R.mergeDeepRight, {}))
Subscribe to RECodes
Get the latest posts delivered right to your inbox