Created
December 20, 2016 10:00
-
-
Save kbariotis/144c9a58948748d236fb14b80565eeb6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const sortModule = require('./sort'); | |
/* Example array */ | |
const array = [ | |
{ | |
name: 'Kostas', | |
age: 28 | |
}, | |
{ | |
name: 'Helen', | |
age: 25 | |
}, | |
{ | |
name: 'George', | |
age: 32 | |
} | |
]; | |
const a = sortModule.sortArray(array, 'age'); | |
console.log(a); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
module.exports.sortArray = (array, sortingField) => { | |
const clone = array.slice(0); // clone so the original stays intact | |
return clone.sort((a, b) => sorter(a, b, sortingField)); | |
}; | |
const sorter = (a, b, sortingField) => { | |
const n1 = a[sortingField]; | |
const n2 = b[sortingField]; | |
if (!Number.isInteger(n1) || !Number.isInteger(n2)) { | |
throw new Error('Not an integer passed'); | |
} | |
return n1 > n2 ? 1 : -1; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const assert = require('assert'); | |
const sortModule = require('./sort'); | |
/* Example array */ | |
const array = [ | |
{ | |
name: 'Kostas', | |
age: 28 | |
}, | |
{ | |
name: 'Helen', | |
age: 25 | |
}, | |
{ | |
name: 'George', | |
age: 32 | |
} | |
]; | |
const a = sortModule.sortArray(array, 'age'); | |
assert.equal(a[0].age, 25); | |
assert.equal(a[1].age, 28); | |
assert.equal(a[2].age, 32); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment