Created
February 20, 2019 14:51
-
-
Save phacks/9b483eae36fc952e90ab88d445fbb057 to your computer and use it in GitHub Desktop.
sortObjectByValues
This file contains hidden or 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 toPairs from 'lodash/fp/toPairs'; | |
import fromPairs from 'lodash/fp/fromPairs'; | |
import sortBy from 'lodash/fp/sortBy'; | |
import flow from 'lodash/fp/flow'; | |
/** | |
* Returns the object, sorted by the lexicographical order of its values | |
* | |
* Equivalent to | |
* _(object).toPairs().sortBy(1).fromPairs().value() | |
* but this version benefits from code splitting. | |
* Sources : | |
* - https://github.com/lodash/lodash/issues/1459#issuecomment-253969771 | |
* - https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba | |
*/ | |
export const sortObjectByValues = object => | |
flow( | |
toPairs, | |
sortBy(1), | |
fromPairs | |
)(object); | |
/** | |
* Accompanying test | |
*/ | |
describe('sortObjectByValues', () => { | |
it('should sort an object by its values', () => { | |
const object = { | |
1: 'd', | |
2: 'b', | |
3: 'c', | |
4: 'a', | |
}; | |
expect(sortObjectByValues(object)).toEqual({ | |
4: 'a', | |
2: 'b', | |
3: 'c', | |
1: 'd', | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment