Last active
March 1, 2017 05:59
-
-
Save marksiemers/f9c0b9230ec1c2ea3f63b452168c990f to your computer and use it in GitHub Desktop.
Scoring objects of arrays based on a "criteria" object
This file contains hidden or 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
function isArray(obj) { | |
return (typeof obj !== "undefined" && obj !== null && obj.constructor === Array) | |
} | |
function areArrays() { | |
if (arguments.length === 0){ return null } | |
for (i = 0; i < arguments.length; i++) { | |
if (!isArray(arguments[i])) { return false } | |
} | |
return true | |
} | |
function calculateScore(a,b) { | |
if (areArrays(a, b)) | |
return _.intersection(a,b).length | |
else | |
return 0 | |
} | |
// function calculateScores(criteria,item){ | |
// var score = 0 | |
// _.forEach(criteria, function(value, key) { score += calculateScore(value, item[key]) }) | |
// return score | |
// } | |
function calculateScores(criteria,item){ | |
return _.reduce(criteria, function(sum, value, key) { | |
return sum + calculateScore(value, item[key]); | |
}, 0); | |
} | |
var criteria = { | |
a: [1], | |
b: [20], | |
c: [8] | |
} | |
var items = [ | |
{ | |
a: [1], | |
b: [2], | |
c: [4] | |
}, | |
{ | |
a: [10], | |
b: [23], | |
c: [9] | |
}, | |
{ | |
a: [2], | |
b: [20], | |
c: [8] | |
}, | |
{ | |
a: [1], | |
b: [20], | |
c: [8] | |
} | |
] | |
scores =_.map(items, function(item) { | |
return calculateScores(criteria, item); | |
}, 0); | |
console.log("scores", scores) | |
filtered_items = _.filter(items, function(item) { return calculateScores(criteria, item) > 0; }); | |
sorted_items = _.sortBy(filtered_items, [function(item) { return -calculateScores(criteria, item); }]); | |
console.log("sorted_items", sorted_items) | |
var expected_result = [ | |
{ | |
a: [1], | |
b: [20], | |
c: [8] | |
}, | |
{ | |
a: [2], | |
b: [20], | |
c: [8] | |
}, | |
{ | |
a: [1], | |
b: [2], | |
c: [4] | |
}, | |
]; | |
console.log("Does it work?", _.isEqual(sorted_items, expected_result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment