0.4.2 • Published 4 years ago

useful-object v0.4.2

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

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"; // 49.8K (gzipped: 11.8K)

....

const obj: any = {
    name: {
        firstName: "Avi",
        lastName: "Punes"
    }
};

obj.get("name.firstName"); // return "Avi"

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
); // Avi
const lastName: string = obj.getSafe((obj: MyInterface) => obj.name.lastName); // Punes

toPromise()

const firstName: string = await obj.get("name.firstName").toPromise(); // Avi

toObservable()

obj.get("name.firstName")
    .toObservable()
    .subscribe((firstName: string) => console.log(firstName)); // logs Avi

Promise

delay(milliseconds: number)

const firstName: string = await obj
    .get("name.firstName")
    .toPromise()
    .delay(1000); // Avi after one second

Array

subset(pattern: string): Array

const array = [1, 50, 3, 10];
array.subset("0..1"); // [1, 50]
array.subset("*..1"); // [1, 50]
array.subset("1..2"); // [50, 3]
array.subset("2..*"); // [3, 10]
array.subset("*..*"); // [1, 50, 3, 10]

Function

attempt(defaultValue?: R, reject?: Function): R | undefined

const throwingFunc = () => {
    throw "Some Error";
};
throwingFunc.attempt();
// console.error "Some Error"
// returns undefined

throwingFunc.attempt("Use this default value");
// console.error "Some Error"
// returns "Use this default value"

throwingFunc.attempt("Use this default value", () => {});
// returns "Use this default value"

const notThrowingFunc = () => {
    return 5 * 3;
};

notThrowingFunc.attempt<number>(); // 15

Test

npm test
0.4.2

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago