AlgoDaily Solution
1var assert = require("assert");
2
3class Hashmap {
4 constructor() {
5 this._storage = [];
6 }
7
8 hashStr(str) {
9 let finalHash = 0;
10 for (let i = 0; i < str.length; i++) {
11 const charCode = str.charCodeAt(i);
12 finalHash += charCode;
13 }
14 return finalHash;
15 }
16
17 set(key, val) {
18 let idx = this.hashStr(key);
19
20 if (!this._storage[idx]) {
21 this._storage[idx] = [];
22 }
23
24 this._storage[idx].push([key, val]);
25 }
26
27 get(key) {
28 let idx = this.hashStr(key);
29
30 if (!this._storage[idx]) {
31 return undefined;
32 }
33
34 for (let keyVal of this._storage[idx]) {
35 if (keyVal[0] === key) {
36 return keyVal[1];
37 }
38 }
39 }
40}
41
42try {
43 var dict = new Hashmap();
44 dict.set("james", "123-456-7890");
45 dict.set("jess", "213-559-6840");
46 assert.equal(dict.get("james"), "123-456-7890");
47
48 console.log(
49 "PASSED: " +
50 "`var dict = new Hashmap(); dict.set('jess', '213-559-6840'); dict.set('james', '123-456-7890'); dict.get('james')` should return `'123-456-7890'`"
51 );
52} catch (err) {
53 console.log(err);
54}
55
56try {
57 assert.equal(dict.get("jake"), undefined);
58
59 console.log(
60 "PASSED: " +
61 "`var dict = new Hashmap(); dict.set('jess', '213-559-6840'); dict.set('james', '123-456-7890'); dict.get('jake')` should return `undefined`"
62 );
63} catch (err) {
64 console.log(err);
65}
66
67try {
68 assertIsFunction(dict.set, "Hashmap class has a `set` method");
69
70 console.log("PASSED: " + "Hashmap class has a `set` method");
71} catch (err) {
72 console.log(err);
73}
74
75try {
76 assertIsFunction(dict.get, "Hashmap class has a `get` method");
77
78 console.log("PASSED: " + "Hashmap class has a `get` methods");
79} catch (err) {
80 console.log(err);
81}
82
83function assertIsFunction(f) {
84 return typeof f === "function";
85}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
70
var assert = require('assert');
class Hashmap {
constructor() {
// implement this
}
set(key, val) {
// implement this
}
get(key) {
// implement this
}
hashStr(str) {
let finalHash = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
finalHash += charCode;
}
return finalHash;
}
}
try {
var dict = new Hashmap();
OUTPUT
Results will appear here.