Today, we have the special true confession from Bruce, who wrote some bad code, but at least knows it’s bad.
Bruce is a C# developer. Bruce is not a web developer. Someone around the office, though, had read an article about how TypeScript was closer to “real” languages, like C#, and asked Bruce to do some TypeScript work.
Now, in C# parlance, your key/value pair data-structure is called a Dictionary. So, when Bruce got stuck on how to store key/value pairs in TypeScript, he googled “typescript dictionary”, and got no useful results.
Disappointed, Bruce set out to remedy this absence:
export class KeyValuePair<TKey,TValue> {
Key: TKey;
Value: TValue;
constructor (key: TKey, value: TValue) {
this.Key = key;
this.Value = value;
}
}
export class Dictionary<TKey, TValue>{
private Collection: Array<KeyValuePair<TKey, TValue>>
private IndexMap: Map<TKey, number>
private index: number;
public tryAdd(key: TKey, value: TValue): boolean {
if (this.containsKey(key)) {
return false;
} else {
var kv = new KeyValuePair(key, value);
this.IndexMap.set(kv.Key, this.Collection.push(kv) - 1);
return true;
}
}
public tryRemove(key: TKey): boolean {
var i = this.indexOf(key);
if (i == -1) {
return false;
} else {
this.Collection.splice(i, 1);
this.reMap(i, key);
return true;
}
}
public indexOf(key: TKey): number {
if (this.containsKey(key)) {
return this.IndexMap.get(key);
} else {
return -1;
}
}
public containsKey(key: TKey): boolean {
if (this.IndexMap.has(key)) {
return true;
} else {
return false;
}
}
private reMap(index: number, key: TKey) {
this.index = index;
this.IndexMap.delete(key);
this.IndexMap.forEach((value: number, key: TKey) => {
if (value > this.index) {
this.IndexMap.set(key, value - 1);
}
});
}
//the rest is recreating C# dictionary methods: getKeys(),getValues(), clear(), etc.
}
The dictionary implementation stores an array of key/value pairs. Now, it’d be expensive to have to search every item in the collection to find the appropriate key/value pair, so Bruce knew he needed to find a way to map keys to values. So he used a Map
to store pairs of keys and indexes within the array.
He spent an entire afternoon coding this masterpiece before realizing that Map
s stored key/value pairs… just like a dictionary.