Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type KeyValuePair<T> = {
- Key: string;
- Value: T;
- }
- interface IDictionary<T>
- {
- Add(key: string, value: T): boolean;
- Remove(key: string): boolean;
- ContainsKey(key: string): boolean;
- Keys: string[];
- Values: T[];
- }
- class Dictionary<T> implements IDictionary<T>
- {
- private items: { [index: string]: T } = {};
- constructor(init?: { key: string; value: T; }[]) {
- if (init) {
- for (var x = 0; x < init.length; x++) {
- this.items[init[x].key] = init[x].value;
- }
- }
- }
- public Add(key: string, value: T): boolean {
- if (this.ContainsKey(key))
- {
- return false;
- }
- this.items[key] = value;
- return this.ContainsKey(key);
- }
- public Remove(key: string): boolean
- {
- if (this.ContainsKey(key))
- {
- delete this.items[key];
- return !this.ContainsKey(key);
- }
- return false;
- }
- public get Keys(): string[]
- {
- return Object.keys(this.items);
- }
- public get Values(): T[]
- {
- return Object.keys(this.items).map(key => this.items[key]);
- }
- public get KeyValuePairs(): KeyValuePair<T>[] {
- return Object.keys(this.items).map(key =>
- (<KeyValuePair<T>>{ Key: key, Value: this.items[key] })
- );
- }
- public ContainsKey(key: string)
- {
- if (typeof this.items[key] === "undefined") {
- return false;
- }
- return true;
- }
- }
- let mydic = new Dictionary<string>();
- mydic.Add("siema", "lol");
- mydic.Add("siema2", "lol");
- let button = document.createElement('button');
- button.textContent = "Say Hello";
- button.onclick = function () {
- for (let item of mydic.KeyValuePairs) {
- alert(item);
- }
- }
- document.body.appendChild(button);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement