Skip to content

Commit

Permalink
add order by behaviour with array similar to get method (lodash#4453)
Browse files Browse the repository at this point in the history
* add order by behaviour with array similar to get method

* remove typo for fixing orderby iteratee assignment

* lint fixes

* update test case

* include package-lock from master

* Add identity function for default iteratee
  • Loading branch information
Mohit21GoJs authored and jdalton committed Aug 30, 2019
1 parent ad38dc0 commit 5df1777
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
11 changes: 10 additions & 1 deletion .internal/baseOrderBy.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import baseEach from './baseEach.js'
import baseSortBy from './baseSortBy.js'
import baseGet from './baseGet.js'
import compareMultiple from './compareMultiple.js'
import isArrayLike from '../isArrayLike.js'

// As existing identity function is in ../test/utils.js, so defining it here, it can be moved to utils
const identity = value => value;

/**
* The base implementation of `orderBy` without param guards.
*
Expand All @@ -15,7 +19,12 @@ import isArrayLike from '../isArrayLike.js'
function baseOrderBy(collection, iteratees, orders) {
let criteriaIndex = -1
let eachIndex = -1
iteratees = iteratees.length ? iteratees : [(value) => value]
iteratees = iteratees.length ? iteratees.map((iteratee) => {
if (Array.isArray(iteratee)) {
return (value) => baseGet(value, iteratee)
}
return iteratee
}) : [identity]

const result = isArrayLike(collection) ? new Array(collection.length) : []

Expand Down
18 changes: 18 additions & 0 deletions test/orderBy.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,29 @@ describe('orderBy', function() {
{ 'a': 'y', 'b': 2 }
];

var nestedObj = [
{ id: '4', address: { zipCode: 4, streetName: 'Beta' } },
{ id: '3', address: { zipCode: 3, streetName: 'Alpha' } },
{ id: '1', address: { zipCode: 1, streetName: 'Alpha' } },
{ id: '2', address: { zipCode: 2, streetName: 'Alpha' } },
{ id: '5', address: { zipCode: 4, streetName: 'Alpha' } },
];


it('should sort by a single property by a specified order', function() {
var actual = orderBy(objects, 'a', 'desc');
assert.deepStrictEqual(actual, [objects[1], objects[3], objects[0], objects[2]]);
});

it('should sort by nested key in array format', () => {
var actual = orderBy(
nestedObj,
[['address','zipCode'], ['address.streetName']],
['asc', 'desc'],
);
assert.deepStrictEqual(actual, [nestedObj[2], nestedObj[3], nestedObj[0], nestedObj[1]], nestedObj[4]);
});

it('should sort by multiple properties by specified orders', function() {
var actual = orderBy(objects, ['a', 'b'], ['desc', 'asc']);
assert.deepStrictEqual(actual, [objects[3], objects[1], objects[2], objects[0]]);
Expand Down

0 comments on commit 5df1777

Please sign in to comment.