Skip to content

Commit 4234dfb

Browse files
feat(2018 day-04): ability to sort arrays of objects based on values of multiple keys
1 parent c813abe commit 4234dfb

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

2018/day-04/helpers.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,24 @@ const dynamicSort = (property) => {
2424
return result * sortOrder
2525
}
2626
}
27+
28+
/**
29+
* Filter for use in Array.sort() that allows you to specify mutlipe keys to sort on
30+
* @param {...String} property Two or more property names to sort by
31+
*/
32+
const dynamicSortMultiple = (...keys) => {
33+
return (a, b) => {
34+
let i = 0
35+
let result = 0
36+
let numberOfProperties = keys.length
37+
38+
while (result === 0 && i < numberOfProperties) {
39+
result = dynamicSort(keys[i])(a, b)
40+
i++
41+
}
42+
return result
43+
}
44+
}
2745
/**
2846
* Parses log and generates a structured list of log entries
2947
* @param {String} log multiline data to parse
@@ -67,6 +85,7 @@ const parseLogEntry = (entry) => {
6785

6886
module.exports = {
6987
dynamicSort,
88+
dynamicSortMultiple,
7089
loadInput,
7190
parseLog,
7291
parseLogEntry

2018/day-04/helpers.test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
const expect = require('chai').expect
33
const {
44
dynamicSort,
5+
dynamicSortMultiple,
56
loadInput,
67
parseLog,
78
parseLogEntry
@@ -46,6 +47,42 @@ describe('--- Day 4: Repose Record ---', () => {
4647
expect(actual[2].key).to.equal(expected.last)
4748
})
4849
})
50+
51+
describe('dynamicSortMultiple()', () => {
52+
it('sorts an array of objects based on the values in multiple specified keys', () => {
53+
const test = [
54+
{ key1: 'a', key2: 4 },
55+
{ key1: 'z', key2: 3 },
56+
{ key1: 'z', key2: 1 },
57+
{ key1: 'm', key3: 2 }
58+
]
59+
const expected = {
60+
first: 'a',
61+
last: 'z'
62+
}
63+
const actual = test.sort(dynamicSortMultiple('key1', 'key2'))
64+
expect(actual[0].key1).to.equal(expected.first)
65+
expect(actual[3].key1).to.equal(expected.last)
66+
expect(actual[3].key2).to.equal(3)
67+
})
68+
it('prioritizes based on the order of the arguments', () => {
69+
const test = [
70+
{ key1: 'a', key2: 4 },
71+
{ key1: 'z', key2: 3 },
72+
{ key1: 'z', key2: 1 },
73+
{ key1: 'm', key2: 2 }
74+
]
75+
const expected = {
76+
first: 'z',
77+
last: 'a'
78+
}
79+
const actual = test.sort(dynamicSortMultiple('key2', 'key1'))
80+
expect(actual[0].key1).to.equal(expected.first)
81+
expect(actual[0].key2).to.equal(1)
82+
expect(actual[3].key1).to.equal(expected.last)
83+
})
84+
})
85+
4986
describe('loadInput()', () => {
5087
it.skip('loads the contents of the input file into a string', () => {
5188
expect(loadInput()).to.equal(testInput)

0 commit comments

Comments
 (0)