Skip to content

Commit b139f35

Browse files
committed
orderBy can take a Function as its first argument
1 parent 9ab6e2a commit b139f35

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/filters/array-filters.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,16 +74,21 @@ export function filterBy (arr, search, delimiter) {
7474
/**
7575
* Filter filter for arrays
7676
*
77-
* @param {String|Array<String>} sortKeys
77+
* @param {String|Array<String>|Function} sortKeys
7878
* @param {Number} [order]
7979
*/
8080

8181
export function orderBy (arr, sortKeys, order) {
8282
arr = convertArray(arr)
8383
order = (order && order < 0) ? -1 : 1
84+
let recursiveCompare = null
8485

8586
if (typeof sortKeys === 'string') {
8687
sortKeys = [sortKeys]
88+
} else if (typeof sortKeys === 'function') {
89+
recursiveCompare = function (a, b) {
90+
return sortKeys(a, b) * order
91+
}
8792
} else if (!sortKeys || (sortKeys !== true && !sortKeys.length)) {
8893
// we check if sortKeys === true because you can sort primitive values with
8994
// array | orderBy true: http://vuejs.org/api/#orderBy
@@ -101,7 +106,7 @@ export function orderBy (arr, sortKeys, order) {
101106
return a === b ? 0 : a > b ? order : -order
102107
}
103108

104-
function recursiveCompare (a, b, i) {
109+
recursiveCompare = recursiveCompare || function (a, b, i) {
105110
i = i || 0
106111
if (sortKeys === true || i === sortKeys.length - 1) {
107112
return compare(a, b, i)

test/unit/specs/filters/filters_spec.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,27 @@ describe('Filters', function () {
264264
res = filter(arr, ['a', 'b'], -1)
265265
assertArray(res, [arr[2], arr[0], arr[3], arr[1], arr[5], arr[4]])
266266
})
267+
268+
it('orderBy using a compare function', function () {
269+
var filter = filters.orderBy
270+
var arr = [9, 11, 1, 2]
271+
var res = filter(arr, evenBeforeOdd)
272+
assertArray(res, [arr[3], arr[2], arr[0], arr[1]])
273+
res = filter(arr, evenBeforeOdd, 1)
274+
assertArray(res, [arr[3], arr[2], arr[0], arr[1]])
275+
res = filter(arr, evenBeforeOdd, -1)
276+
assertArray(res, [arr[1], arr[0], arr[2], arr[3]])
277+
})
267278
})
268279

280+
function evenBeforeOdd (a, b) {
281+
if (a % 2 === 0) {
282+
if (b % 2 === 0) return a - b
283+
else return -1
284+
} else if (b % 2 === 0) return 1
285+
else return a - b
286+
}
287+
269288
function assertArray (res, expectations) {
270289
expect(res.length).toBe(expectations.length)
271290
expectations.forEach(function (exp, i) {

0 commit comments

Comments
 (0)