@gxyz/util v0.2.0
@gxyz/util
@gxyz/util is a lightweight utility library.
Installation
Install the module locally via your favorite npm client, like npm:
npm install @gxyz/utilor yarn:
yarn add @gxyz/utilUsage
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
…functionsare fulfilled, returned obj will have avalueprop with the reduced value. - If any of
…functionsis rejected, returned obj will have areasonprop 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
funcis fulfilled, returned obj will have avalueprop with returned value. - If
funcis rejected, returned obj will have areasonprop 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 |
