8000 Implement Dictionary.from(Object) · HowProgrammingWorks/Map@586b54a · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 586b54a

Browse files
committed
Implement Dictionary.from(Object)
1 parent dc26ddd commit 586b54a

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

JavaScript/1-object.js

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,26 +25,44 @@ class Dictionary {
2525
clear() {
2626
this.map = Object.create(null);
2727
}
28+
static from(hash) {
29+
const instance = new Dictionary();
30+
for (const key in hash) {
31+
instance.set(key, hash[key]);
32+
}
33+
return instance;
34+
}
2835
}
2936

3037
// Usage
3138

32-
const cityPopulation = new Dictionary();
39+
const cities = {
40+
Shanghai: 24256800,
41+
Beijing: 21516000,
42+
Delhi: 16787941,
43+
Lagos: 16060303
44+
};
45+
46+
const cityPopulation1 = Dictionary.from(cities);
47+
console.dir({ cityPopulation1 });
3348

34-
cityPopulation.set('Shanghai', 24256800);
35-
cityPopulation.set('Beijing', 21516000);
36-
cityPopulation.set('Delhi', 16787941);
37-
cityPopulation.set('Lagos', 16060303);
49+
const cityPopulation2 = new Dictionary();
50+
cityPopulation2.set('Shanghai', 24256800);
51+
cityPopulation2.set('Beijing', 21516000);
52+
cityPopulation2.set('Delhi', 16787941);
53+
cityPopulation2.set('Lagos', 16060303);
54+
console.dir({ cityPopulation2 });
3855

39-
cityPopulation.delete('Shanghai');
56+
cityPopulation2.delete('Shanghai');
57+
console.dir({ cityPopulation2 });
4058

41-
if (cityPopulation.has('Beijing')) {
42-
console.log('Beijing:', cityPopulation.get('Beijing'));
59+
if (cityPopulation2.has('Beijing')) {
60+
console.log('Beijing:', cityPopulation2.get('Beijing'));
4361
}
4462

45-
if (!cityPopulation.has('Shanghai')) {
63+
if (!cityPopulation2.has('Shanghai')) {
4664
console.log('no data for Shanghai');
4765
}
4866

49-
console.log('size:', cityPopulation.size);
50-
console.log('keys:', cityPopulation.keys());
67+
console.log('size:', cityPopulation2.size);
68+
console.log('keys:', cityPopulation2.keys());

0 commit comments

Comments
 (0)
0