@gxyz/util

0.2.0 • Public • Published

@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 a value prop with the reduced value.
  • If any of …functions is rejected, returned obj will have a reason 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 a value prop with returned value.
  • If func is rejected, returned obj will have a reason 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

Using toString() to detect object class

const {toString,} = str;

toString(new Error()) === 'Error';

Credits

Aziz Da
Aziz Da

License

Unlicense

Package Sidebar

Install

npm i @gxyz/util

Weekly Downloads

3

Version

0.2.0

License

Unlicense

Unpacked Size

5.05 kB

Total Files

7

Last publish

Collaborators

  • gxyz.js