Skip to content

Instantly share code, notes, and snippets.

@ClementParis016
Created February 1, 2019 10:32
Show Gist options
  • Save ClementParis016/5fb17f768b0c17a5ebe08cdbdb52bda5 to your computer and use it in GitHub Desktop.
Save ClementParis016/5fb17f768b0c17a5ebe08cdbdb52bda5 to your computer and use it in GitHub Desktop.
Lodash's missing swap util to replace an element from a collection
import { map, iteratee } from 'lodash';
/**
* Replaces elements from collection that matches predicate with replacement.
*
* @param {Array} collection The collection to replace in
* @param {*} predicate The condition to determine which elements of collection
* should be replaced
* @param {*} replacement The value to use as a replacement of elements of
* collection that matches the predicate
*/
export const swap = (collection, predicate, replacement) => {
const condition = iteratee(predicate);
return map(collection, (element) => {
if (condition(element)) {
return replacement;
}
return element;
});
};
describe('#swap()', () => {
it('replaces element from collection that matches predicate', () => {
const collection = [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
];
const predicate = { id: 2 };
const replacement = { id: 4, value: 'four' };
const expected = [
{ id: 1, value: 'one' },
{ id: 4, value: 'four' },
{ id: 3, value: 'three' },
];
expect(swap(collection, predicate, replacement)).toEqual(expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment