I recently implemented a dictionary class in TypeScript. I'm still new to JavaScript so I'm curious what people think about it.
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 getKeys(): string[] {
let result = [];
for (let item in this) {
if (this.hasOwnProperty(item)) {
result.push(item);
}
}
return result;
}
public getValues(): any[] {
let result = [];
for (let item in this) {
if (this.hasOwnProperty(item)) {
result.push(this[item]);
}
}
return result;
}
public tryAddItem(key: string, value: any): boolean {
let isAddItem = !this.hasOwnProperty(key) && typeof(value) !== 'undefined';
if (isAddItem) {
this[key] = value;
}
return isAddItem;
}
public tryUpdateItem(key: string, value: any): boolean {
let isUpdateItem = this.hasOwnProperty(key) && typeof(value) !== 'undefined';
if (isUpdateItem) {
this[key] = value;
}
return isUpdateItem;
}
public tryDeleteItem(key: string): boolean {
let isDeleteItem = this.hasOwnProperty(key);
if (isDeleteItem) {
delete this[key];
}
return isDeleteItem;
}
}
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. \$\endgroup\$