Skip to content

Commit a80242b

Browse files
author
bjvickers
committed
feat: add support for descending sort
second draft, await integration of custom sort into new function fixes issue #6
1 parent 71d95b6 commit a80242b

File tree

3 files changed

+344
-13
lines changed

3 files changed

+344
-13
lines changed

index.js

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -127,16 +127,16 @@ function sortByCustom (properties, customOrder) {
127127
function sortByConvention (sortBy) {
128128
let sorts = sortBy.slice(0)
129129
let propSort = sorts.shift()
130-
let property = t.isArrayLike(propSort) && propSort.shift() || undefined
131-
let sort = t.isArrayLike(propSort) && propSort.shift() || 'asc'
130+
let property = t.isArrayLike(propSort) && propSort[0] || undefined
131+
let sort = t.isArrayLike(propSort) && propSort[1] || 'asc'
132132

133133
return function sorter (a, b) {
134134
// Sort asc initially, then invert the result if a desc has been requested
135-
136135
let result
137136
const x = a[property]
138137
const y = b[property]
139138
let currentSort = sort
139+
let recurse
140140

141141
// Perform the initial asc sort
142142
if (x === null && y === null) {
@@ -151,21 +151,27 @@ function sortByConvention (sortBy) {
151151
result = x < y ? -1 : x > y ? 1 : 0
152152
}
153153

154-
// Prepare the for the next call to this sorting function
155-
if (!((result === 0) && (sorts.length))) {
154+
// Reset this sorting function and parent, unless we have an equal
155+
// result and there are more sorts still to perform, in which case
156+
// move on to the next one.
157+
if (result === 0 && sorts.length) {
158+
recurse = true
159+
} else {
160+
recurse = false
156161
sorts = sortBy.slice(0)
157162
}
158-
propSort = sorts.shift()
159-
property = t.isArrayLike(propSort) && propSort.shift() || undefined
160-
sort = t.isArrayLike(propSort) && propSort.shift() || 'asc'
161163

164+
propSort = sorts.shift()
165+
property = t.isArrayLike(propSort) && propSort[0] || undefined
166+
sort = t.isArrayLike(propSort) && propSort[1] || 'asc'
167+
162168
// Present the result
163-
if ((result === 0) && (sorts.length)) {
169+
if (recurse) {
164170
return sorter(a, b)
165171
} else if ((result === 0) || (currentSort === 'asc')) {
166172
return result
167173
} else {
168-
return result *= -1
174+
return result * -1
169175
}
170176
}
171177
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
},
2121
"scripts": {
2222
"test": "test-runner test/*.js",
23-
"test:next": "test-runner test/sort-order.js",
23+
"test:next": "node test/sort-order.js",
2424
"docs": "jsdoc2md -t README.hbs index.js > README.md; echo"
2525
},
2626
"dependencies": {

0 commit comments

Comments
 (0)