Created
January 5, 2022 13:19
-
-
Save vladislavaSim/8a00aced1a97cac871b59fe4a6de198c to your computer and use it in GitHub Desktop.
sorting objects
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
let collection = [ | |
{ | |
name: 'John', | |
age: 18, | |
friendsCount: 22 | |
}, | |
{ | |
name: 'Eve', | |
age: 17, | |
friendsCount: 14 | |
}, | |
{ | |
name: 'Helen', | |
age: 28, | |
friendsCount: 48 | |
} | |
]; | |
let collection1 = [ | |
{ | |
name: 'Max', | |
age: 22, | |
friendsCount: 32 | |
} | |
]; | |
function compare(a, b, property) { | |
if (a[property] < b[property]) { | |
return -1; | |
} else if (a[property] > b[property]) { | |
return 1; | |
} | |
return 0; | |
} | |
function makeCondition(propertyName, direction) { | |
return function (a, b) { | |
if (direction === 'desc') { | |
let c; | |
c = a; | |
a = b; | |
b = c; | |
} | |
return compare(a, b, propertyName); | |
} | |
} | |
function applyConditions(conditions) { | |
return function (a,b) { | |
let result = 0; | |
let i = 0; | |
do { | |
result = conditions[i++](a,b) | |
} while (result === 0 && i < conditions.length); | |
console.log(result) | |
return result; | |
} | |
} | |
function sort(...collections) { | |
let collection = [].concat(...collections); | |
let conditions = []; | |
function part(propertyName, direction = 'asc') { | |
if(!propertyName || !direction){ | |
return collection.sort(applyConditions(conditions)) | |
} | |
conditions.push(makeCondition(propertyName, direction)); | |
return part; | |
} | |
return part; | |
} | |
let result = sort(collection,collection1)('salary','desc')('name','desc')('age')(); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment