-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-inventory-in-your-smartphone-store.js
60 lines (43 loc) · 1.79 KB
/
update-inventory-in-your-smartphone-store.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
/**
* http://www.codewars.com/kata/update-inventory-in-your-smartphone-store/
*
You will be given an array which lists the current inventory of stock in your store. Example:
var currentInventory = [ [25, 'HTC'], [1000, 'Nokia'], [50, 'Samsung'], [33, 'Sony'], [10, 'Apple'] ];
Your will also be given an array which list the new inventory being delivered to your store today. Example:
var newInventory = [ [5, 'LG'], [10, 'Sony'], [4, 'Samsung'], [5, 'Apple'] ];
Your task is to write a function that when invoked
updateInventory(currentInventory, newInventory);
returns the updated list of your current inventory in alphabetical order:
[[15,'Apple'],[25,'HTC'],[5,'LG'],[1000,'Nokia'],[54,'Samsung'],[43,'Sony']]
Please note however that the input arrays may not necessarily be passed in alphabetical order.
Kata inspirad by the FreeCodeCamp's 'Inventory Update' algorithm
*
*/
let tests = require('./lib/framework.js');
let Test = tests.Test, describe = tests.describe, it = tests.it, before = tests.before, after = tests.after;
function updateInventory(curStock, newStock) {
const hash = curStock.concat(newStock).reduce((carry, x) => {
let k = x[1];
if (!carry[k]) carry[k] = 0;
carry[k] += x[0];
return carry;
}, {});
return Object.keys(hash).reduce((carry, x) => {
carry.push([hash[x], x]);
return carry;
}, []).sort((a, b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0);
}
var currentInventory = [
[25, 'HTC'],
[1000, 'Nokia'],
[50, 'Samsung'],
[33, 'Sony'],
[10, 'Apple']
];
var newInventory = [
[5, 'LG'],
[10, 'Sony'],
[4, 'Samsung'],
[5, 'Apple']
];
Test.assertSimilar(updateInventory(currentInventory, newInventory), [[15,'Apple'],[25,'HTC'],[5,'LG'],[1000,'Nokia'],[54,'Samsung'],[43,'Sony']]);