-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathspreadsheet.js
More file actions
67 lines (50 loc) · 1.58 KB
/
spreadsheet.js
File metadata and controls
67 lines (50 loc) · 1.58 KB
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
/*
Write a class called Spreadsheet that will write (put) and obtain (get) values from a table
like in Excel. You can assume that values accessed will exist, but we may want to create a
caching system in order to avoid multiple highly intensive computational actions.
*/
class Spreadsheet {
constructor() {
this.cache = {};
this.cells = {};
this.graph = {};
}
put = (key, value) => {
this.cells[key] = value;
this._recursivelyClearCache(key);
this.graph[key] = [];
};
get = (key) => {
if (this.cache[key]) {
return this.cache[key];
}
const value = this.cells[key];
const valuesArray = value.split("=").join("").split("+");
let total = 0;
for (const currentValue of valuesArray) {
const convertedValue = parseInt(currentValue, 10);
if (isNaN(convertedValue)) {
total += this.get(currentValue);
this._addGraphDependency(currentValue, key);
} else {
total += convertedValue;
}
}
this.cache[key] = total;
return total;
};
_recursivelyClearCache = (key) => {
delete this.cache[key];
if (!this.graph[key]) {
this.graph[key] = [];
}
this.graph[key].forEach((dep) => {
this._recursivelyClearCache(dep);
});
};
_addGraphDependency = (child, parent) => {
this.graph[child] = this.graph[child] || [];
this.graph[child].push(parent);
};
}
module.exports = Spreadsheet;