I recently implemented a dictionary class in typescript. I'm still new to javascript so I'm curious what people think about it.
One Update
class Dictionary {
public constructor ();
public constructor (object: Object);
public constructor (object?) {
if (object != null) {
for (let property in object) {
if (object.hasOwnProperty(property)) {
this[property] = object[property];
}
}
}
}
public clone(): Dictionary {
let result = new Dictionary(this);
return result;
}
public exists(key: string): boolean {
let result = this.hasOwnProperty(key);
return result;
}
public keys(): string[] {
let result = [];
for (let key in this) {
if (this.hasOwnProperty(key)) {
result.push(key);
}
}
return result;
}
public values(): any[] {
let result = [];
for (let key in this) {
if (this.hasOwnProperty(key)) {
result.push(this[key]);
}
}
return result;
}
public tryAdd(key: string, value: any): boolean {
let isAddItem = !this.exists(key) && typeof(value) !== 'undefined';
if (isAddItem) {
this[key] = value;
}
return isAddItem;
}
public tryUpdate(key: string, value: any): boolean {
let isUpdateItem = this.exists(key) && typeof(value) !== 'undefined';
if (isUpdateItem) {
this[key] = value;
}
return isUpdateItem;
}
public tryDelete(key: string): boolean {
let isDeleteItem = this.exists(key);
if (isDeleteItem) {
delete this[key];
}
return isDeleteItem;
}
}
Ramblings
I realized that objects in javascript act a lot like dictionaries so I'm basically just adding functionality to the object. I'm not sure how I would want to handle sorting. I think I would prefer to create a method that returned a sorted array or object based on some function. Similar to what a javascript linq library would do.
Map
could help with some stuff. – gcampbell Jul 6 at 17:08