@gxyz/util
@gxyz/util is a lightweight utility library.
Installation
Install the module locally via your favorite npm client, like npm:
npm install @gxyz/util
or yarn:
yarn add @gxyz/util
Usage
func
You can use func'utilities from the main entry:
const {func,} = require('@gxyz/util');
Or from the custom subpath ./func
:
const func = require('@gxyz/util/func');
This path is not recommended:
const func = require('@gxyz/util/lib/func');
promises
const {promises: {compose, tryCatch,},} = func;
compose
Compose async funcs. Take a look at the MDN Web Docs - Using Promises - Composition.
Compose takes an arguments object of async funcs or promises or an array of async funcs or promises.
Compose returns a function, arguments object passed to this function will be used as arguments object of the first element of …functions
.
Compose returned func returns an object as promise:
- If all
…functions
are fulfilled, returned obj will have avalue
prop with the reduced value. - If any of
…functions
is rejected, returned obj will have areason
prop with err.
async function dealAsyncFuncs(...args) {
const {reason, value,} = await compose(func0, func1, func2)(...args);
if (reason instanceof Error) {
throw reason;
}
return value;
}
tryCatch
Better manage errors within async funcs.
tryCatch takes an async func or a promise as arg.
tryCatch returns a function, arguments object passed to this function will be used as argument object to func
.
tryCatch returned func returns an object as promise:
- If
func
is fulfilled, returned obj will have avalue
prop with returned value. - If
func
is rejected, returned obj will have areason
prop with err.
async function dealAsyncFunc(...args) {
const {reason, value,} = await tryCatch(func)(...args);
if (reason instanceof Error) {
throw reason;
}
return value;
}
str
You can use str'utilities from the main entry:
const {str,} = require('@gxyz/util');
Or from the custom subpath ./str
:
const str = require('@gxyz/util/str');
This path is not recommended:
const str = require('@gxyz/util/lib/str');
toString
const {toString,} = str;
toString(new Error()) === 'Error';
Credits
Aziz Da |