Home Reference Source Repository

src/utils/data.js

import {find, findIndex, propEq, compose} from 'ramda';

/**
 * Finds the index of an element in an array by comparing defined identifying property.
 * @type {Function}
 * @returns {number} The targeted element index.
 * @example
 * let resultIndex = findBy('id', 1)(elements);
 */
export const findBy = compose(findIndex, propEq);
/**
 * Gets an element in an array by comparing defined identifying property.
 * @type {Function}
 * @returns {Object} The targeted element.
 * @example
 * let result = getBy('id', 1)(elements);
 */
export const getBy = compose(find, propEq);
/**
 * Gets the next available identifier for pushing a keyed element into the array.
 * @type {Function}
 * @param {Array} items The target array.
 * @returns {number} The next free identifier.
 * @example
 * let nextId = getId(elements);
 */
export const getId = items => items.length ? items[items.length - 1].id + 1 : 1;