Skip to content

Commit 6c570dd

Browse files
committed
test/docs: add test and docs for the custom sort function parameter
1 parent eedb279 commit 6c570dd

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,43 @@ console.log(output)
4747

4848
```
4949

50+
## Optional parameters
51+
52+
### Custom sort function
53+
54+
You can pass a custom sort function as the second argument. This function is passed to the Javascript <code>sort</code> function, that sorts in alphabetical order by default. The custom function should return zero, a negative or positive value:
55+
56+
```js
57+
var reverseAlphabeticalSort = function (a, b) {
58+
return a < b
59+
}
60+
61+
var object = {
62+
a: {
63+
a: 0,
64+
c: ['c', 'a', 'b'],
65+
b: 0
66+
},
67+
c: 0,
68+
b: 0
69+
}
70+
71+
var output = sort(object, reverseAlphabeticalSort)
72+
73+
console.log(output)
74+
75+
// {
76+
// c: 0,
77+
// b: 0,
78+
// a: {
79+
// c: ['c', 'b', 'a'],
80+
// b: 0,
81+
// a: 0
82+
// }
83+
// }
84+
85+
```
86+
5087
## License
5188

5289
MIT © [Kiko Beats](http://www.kikobeats.com)

test/test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,34 @@ test('sort object', (t) => {
6868
}
6969
t.deepEqual(sort(object), sorted)
7070
})
71+
72+
test('sort object > compareFn', (t) => {
73+
const input = {
74+
a: {
75+
a: 0,
76+
c: ['c', 'a', 'b'],
77+
b: 0
78+
},
79+
c: 0,
80+
b: 0
81+
}
82+
83+
const expectedResult = {
84+
c: 0,
85+
b: 0,
86+
a: {
87+
c: ['c', 'b', 'a'],
88+
b: 0,
89+
a: 0
90+
}
91+
}
92+
93+
// Sort in reverse alphabetical order (instead of the default alphabetical order).
94+
const result = sort(input, (a, b) => a < b)
95+
96+
t.deepEqual(result, expectedResult)
97+
98+
// Check the ordering of the keys.
99+
t.deepEqual(Object.keys(result), Object.keys(expectedResult))
100+
t.deepEqual(Object.keys(result.a), Object.keys(expectedResult.a))
101+
})

0 commit comments

Comments
 (0)