Map Sum Pairs LeetCode solution in JavaScript

1
var MapSum = function () {
2
this.hashKeys = new Map();
3
this.hashVals = new Map();
4
};
5

6
MapSum.prototype.insert = function (key, val) {
7
let prefix = "";
8
for (const str of key) {
9
prefix += str;
10
const hashKey = this.hashKeys.get(prefix) ?? new Set();
11
hashKey.add(key);
12
!this.hashKeys.has(prefix) && this.hashKeys.set(prefix, hashKey);
13
}
14
this.hashVals.set(key, val);
15
};
16

17
MapSum.prototype.sum = function (prefix) {
18
const hashKey = this.hashKeys.get(prefix);
19
if (!hashKey) return 0;
20
let sum = 0;
21
hashKey.forEach((key) => (sum += this.hashVals.get(key)));
22
return sum;
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0