Useful Object
Typescript util to add useful methods to global Object, Array and more types.
Installation
npm install useful-object --save
Usage
Object
get(path: string, defaultValue?: any)
import "useful-object";
....
const obj: any = {
name: {
firstName: "Avi",
lastName: "Punes"
}
};
obj.get("name.firstName");
Need type safety? use getSafe<ObjectType, ExpectedReturnType>(function(obj: ObjectType): ExpectedReturnType)
interface MyInterface {
name: {
firstName: string;
lastName: string;
};
}
const obj: MyInterface = {
name: {
firstName: "Avi",
lastName: "Punes"
}
};
const firstName: string = obj.getSafe<MyInterface, string>(
obj => obj.name.firstName
);
const lastName: string = obj.getSafe((obj: MyInterface) => obj.name.lastName);
toPromise()
const firstName: string = await obj.get("name.firstName").toPromise();
toObservable()
obj.get("name.firstName")
.toObservable()
.subscribe((firstName: string) => console.log(firstName));
Promise
delay(milliseconds: number)
const firstName: string = await obj
.get("name.firstName")
.toPromise()
.delay(1000);
Array
subset(pattern: string): Array
const array = [1, 50, 3, 10];
array.subset("0..1");
array.subset("*..1");
array.subset("1..2");
array.subset("2..*");
array.subset("*..*");
Function
attempt(defaultValue?: R, reject?: Function): R | undefined
const throwingFunc = () => {
throw "Some Error";
};
throwingFunc.attempt();
throwingFunc.attempt("Use this default value");
throwingFunc.attempt("Use this default value", () => {});
const notThrowingFunc = () => {
return 5 * 3;
};
notThrowingFunc.attempt<number>();
Test
npm test