Last active
December 28, 2015 22:46
-
-
Save cilerler/5477f8a6024d4b2ec379 to your computer and use it in GitHub Desktop.
Dictionary<T>
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
module Generic { | |
"use strict"; | |
export class KeyValuePair<T> { | |
private _key: string; | |
get Key(): string { | |
return this._key; | |
} | |
set Key(key: string) { | |
this._key = key; | |
} | |
private _value: T; | |
get Value(): T { | |
return this._value; | |
} | |
set Value(value: T) { | |
this._value = value; | |
} | |
constructor(key: string, value: T) { | |
this._key = key; | |
this._value = value; | |
} | |
} | |
export class Dictionary<T> { | |
private _wordUndefined = "undefined"; | |
private _items: KeyValuePair<T>[] = []; | |
GetEnumerator(): KeyValuePair<T>[] { | |
return this._items; | |
} | |
Add(key: string, value: T) { | |
const newItem = new KeyValuePair<T>(key, value); | |
if (!this.ContainsKey(key)) { | |
this._items.push(newItem); | |
this._items[key] = value; | |
} | |
} | |
Remove(key: string) { | |
const index = this.indexOf(key); | |
this._items.splice(index, 1); | |
delete this._items[key]; | |
} | |
Count() { | |
return this._items.length; | |
} | |
ContainsKey(key: string) { | |
return !(typeof this._items[key] === this._wordUndefined); | |
} | |
ElementAt(index: number): KeyValuePair<T> { | |
return this._items[index]; | |
} | |
Element(key: string): KeyValuePair<T> { | |
var breakException = {}; | |
var output: KeyValuePair<T>; | |
try { | |
// ReSharper disable UnusedParameter | |
this._items.forEach((element, index, array) => { | |
// ReSharper restore UnusedParameter | |
if (element.Key === key) { | |
output = element; | |
throw breakException; | |
} | |
}); | |
} catch (e) { | |
if (e !== breakException) throw e; | |
} | |
return output; | |
} | |
private indexOf(key: string): number { | |
const item = this.Element(key); | |
if (typeof item === this._wordUndefined) { | |
return -1; | |
} | |
const output = this._items.indexOf(item); | |
return output; | |
} | |
Keys(): string[] { | |
var output: string[] = []; | |
// ReSharper disable UnusedParameter | |
this._items.forEach((element, index, array) => { | |
// ReSharper restore UnusedParameter | |
output.push(element.Key); | |
}); | |
return output; | |
} | |
Values(): T[] { | |
var output: T[] = []; | |
// ReSharper disable UnusedParameter | |
this._items.forEach((element, index, array) => { | |
// ReSharper restore UnusedParameter | |
output.push(element.Value); | |
}); | |
return output; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment