forked from devfacet/knapsack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (52 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* Knapsack
* For the full copyright and license information, please view the LICENSE.txt file.
*/
/* jslint node: true */
'use strict';
// Init the module
module.exports = function() {
// Resolves the given problem
var resolve = function resolve(capacity, items) {
var result = [],
leftCap = capacity,
itemsFiltered;
if(typeof capacity !== 'number')
return false;
if(!items || !(items instanceof Array))
return false;
// Resolve
var item,
itemKey,
itemVal,
itemObj;
itemsFiltered = items.filter(function(value) {
itemVal = (typeof value === 'object') ? value[Object.keys(value)[0]] : null;
if(!isNaN(itemVal) && itemVal > 0 && itemVal <= capacity) {
return true;
} else {
return false;
}
});
itemsFiltered.sort(function(a, b) { return a[Object.keys(a)[0]] < b[Object.keys(b)[0]]; });
for(item in itemsFiltered) {
if(itemsFiltered.hasOwnProperty(item)) {
itemKey = Object.keys(itemsFiltered[item])[0];
itemVal = itemsFiltered[item][itemKey];
if((leftCap-itemVal) >= 0) {
leftCap = leftCap-itemVal;
itemObj = Object.create(null);
itemObj[itemKey] = itemVal;
result.push(itemObj);
delete itemsFiltered[item];
if(leftCap <= 0) break;
}
}
}
return result;
};
// Return
return {
resolve: resolve
};
}();