Created
February 1, 2019 10:32
-
-
Save ClementParis016/5fb17f768b0c17a5ebe08cdbdb52bda5 to your computer and use it in GitHub Desktop.
Lodash's missing swap util to replace an element from a collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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