Created
April 27, 2022 23:46
-
-
Save cesarkohl/9bb49010699f541fa48e630e0f4a8b49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface IKeyCollection<T> { | |
add(key: string, value: T); | |
containsKey(key: string): boolean; | |
size(): number; | |
getItem(key: string): T; | |
removeItem(key: string): T; | |
getKeys(): string[]; | |
values(): T[]; | |
} | |
export default class Dictionary<T> implements IKeyCollection<T> { | |
private items: { [index: string]: T } = {}; | |
private count: number = 0; | |
add(key: string, value: T) { | |
if (!this.items.hasOwnProperty(key)) { | |
this.count++; | |
} | |
this.items[key] = value; | |
} | |
containsKey(key: string): boolean { | |
return this.items.hasOwnProperty(key); | |
} | |
size(): number { | |
return this.count; | |
} | |
getItem(key: string): T { | |
return this.items[key]; | |
} | |
removeItem(key: string): T { | |
let value = this.items[key]; | |
delete this.items[key]; | |
this.count--; | |
return value; | |
} | |
getKeys(): string[] { | |
let keySet: string[] = []; | |
for (let property in this.items) { | |
if (this.items.hasOwnProperty(property)) { | |
keySet.push(property); | |
} | |
} | |
return keySet; | |
} | |
values(): T[] { | |
let values: T[] = []; | |
for (let property in this.items) { | |
if (this.items.hasOwnProperty(property)) { | |
values.push(this.items[property]); | |
} | |
} | |
return values; | |
} | |
} | |
let personHobbies = new Dictionary<string>(); | |
personHobbies.add('jack', 'swimming'); | |
personHobbies.add('mary', 'singing'); | |
personHobbies.add('tom', 'dancing'); | |
const keys = personHobbies.getKeys(); // will return ['jack', 'mary', 'tom'] | |
const values = personHobbies.values(); // will return ['swimming', 'singing', 'dancing'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment