Skip to content

Instantly share code, notes, and snippets.

@phacks
Created February 20, 2019 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phacks/9b483eae36fc952e90ab88d445fbb057 to your computer and use it in GitHub Desktop.
Save phacks/9b483eae36fc952e90ab88d445fbb057 to your computer and use it in GitHub Desktop.
sortObjectByValues
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