0.0.7 • Published 1 year ago

handilities v0.0.7

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

npm version Coverage Status

Handilities

List of handy utilities for JS/TS projects in web and nodejs environments.

Prerequisites

No specific version of nodejs and npm is required, but for the usage as an npm package please install nodejs of your choice.

Table of contents

Installation

BEFORE YOU INSTALL: please read the prerequisites

To install and set up the library, run:

$ npm install -S handilities

Or if you prefer using Yarn:

$ yarn add handilities

API


TS Utilities

KeyOf

type KeyOf<T>;

Utility type that constructs a type consisting of own enumerable keys of a given object.

Example:

type TKey = KeyOf<{ a: 'a', b: 'b' }>;

const key1: TKey = 'a';
const key2: TKey = 'b';
const key3: TKey = 'c'; -> Type '"c"' is not assignable to type '"a" | "b"'.

ValueOf

type ValueOf<T>;

Utility type that constructs a type consisting of values of own enumerable keys of a given object.

Example:

type TValue = ValueOf<{ a: 'a', b: 'b' }>

const value1: TValue = 'a';
const value2: TValue = 'b';
const value3: TValue = 'c'; -> Type '"c"' is not assignable to type 'TValue'.

objectKeys()

objectKeys(target: Record<string, unknown>);

Utility function that returns an array of own enumerable keys of a given object.

Options

NameTypeDefault value
targetObject-

Example:

const car = {
  wheels: 4,
  output: '200 HP',
  name: 'Tesla',
};

// Compare:
const keys1 = Object.keys(car); -> const keys1: string[]
const keys2 = objectKeys(car); -> const keys2: ("wheels" | "output" | "name")[]

Common Utilities

removeByKey()

removeByKey(path: string | string[], target: Record<string, unknown>);

Removes key-value pair in the object by a provided path. Returns new object if the path was successfully resolved. Returns target if the path wasn't resolved.

Options

NameTypeDefault value
pathstring, string[]-
targetObject-

Examples:

// Removes 'b' key in the target object
const target = {
  a: 'A',
  b: 'B',
};

const result = removeByKey('a', target); -> { b: 'B' }

// Removes 'c' key in the target object
const target = {
  a: {
    c: 'C'
  },
  b: 'B',
};

const result = removeByKey(['a', 'c'], target); -> { a: {}, b: 'B' }

// Path isn't resolved
const target = {
  a: 'a',
  b: 'B',
};

const result = removeByKey(['c'], target); -> { a: 'a', b: 'B' }
const targetEqualsResult = result === target; -> true

removeDeepByKey()

removeDeepByKey(path: string[], target: Record<string, unknown>);

Removes key-value pair in the object by a provided path. Also, if deleted key-value was the only one in an object, removes that empty object and recursively checks previous key-value pair for the same. Returns new object if the path was successfully resolved. Returns target if the path wasn't resolved.

Options

NameTypeDefault value
pathstring[]-
targetObject-

Examples:

// Removes 'b' key in the target object
const target = {
  a: 'A',
  b: 'B',
};

const result = removeDeepByKey(['a'], target); -> { b: 'B' }

// Removes 'c' key in the target object, and recursively removes empty "parents"
const target = {
  a: {
    c: 'C'
  },
  b: 'B',
};

const result = removeDeepByKey(['a', 'c'], target); -> { b: 'B' }

// Path isn't resolved
const target = {
  a: 'a',
  b: 'B',
};

const result = removeDeepByKey(['c'], target); -> { a: 'a', b: 'B' }
const targetEqualsResult = result === target; -> true

beautifyNumber()

beautifyNumber(value: number, options: IBeautifyNumberOptions);

Produces a formatted string that was created out of the number provided as an input of the function. Formatting rules:

  • splits a whole part of a number by thousands
  • adds a joint symbol between thousands
  • adds a delimiter symbol between a whole and a floating part

Options

NameTypeRequiredDefault value
valuenumber+-
optionsIBeautifyNumberOptions-{ delimiter: '.', joint: ' ' }

Examples:

// Whole numbers
const result = beautifyNumber(1000); -> '1 000'
const result = beautifyNumber(1_000); -> '1 000'

// With floating point
const result = beautifyNumber(1000.123); -> '1 000.123'
const result = beautifyNumber(1000.123, { delimiter: ',' }); -> '1 000,123'
const result = beautifyNumber(1000.123, { delimiter: ',', joint: '_' }); -> '1_000,123'

// Throws error
const result = beautifyNumber(1000.123, { delimiter: ',', joint: ',' }); -> [Error: Please provide different delimiter and joint values]

List Utils

A common function for initializing a bag of useful traversing utilities for going over, finding and mutating nodes within some nested objects structures. For now, contains following methods:

  • findByPrimaryKey() - finds a node by its primary identifier and invokes provided callback to mutate the node.

Might be useful if you want to create a set of handy functions at one place, binding primary and secondary keys of your list (please refer to the example below).

Options

NameTypeRequiredDefault value
initOptionsIInitListUtilsOptions+-
IInitListUtilsOptions
PropertyTypeDefault value
primaryKeystring-
childrenKeystring-

Examples:

const list = [
  {
    id: '0', // <- primary key
    value: 'v-0',
  },
  {
    id: '1',
    value: 'v-1',
    children: [ // <- children key
      {
        id: '1-1',
        value: 'v-1-1',
      },
    ],
  },
];

const listUtils = initListUtils({ primaryKey: 'id', childrenKey: 'children' });

// Going through the list and finds a node with id === '1-1', returns a link to the found node
listUtils.findByPrimaryKey(list, '1-1'); -> { id: '1-1', value: 'v-1-1' }

For more exhaustive details on the findByPrimaryKey() interface please refer to the corresponding section of this document.

findByPrimaryKey()

findByPrimaryKey(primaryKey: string, childrenKey: string)(
  items: Record<string, unknown>,
  value: any,
  callback?: (node: Record<string, unknown>) => void,
);

This function is a part of the above described List Utils. It is returned as a result of invoking the initListUtils.

Purpose: the utility function that iterates over the list of a nested objects and searches for a particular node by its id. Also, calls provided callback on a found node (if any).

Options

NameTypeRequiredDefault value
primaryKeystring+-
childrenKeystring+-

Returns another function with the following arguments interface:

NameTypeRequiredDefault value
items(T extends Record<string, unknown>)[]+-
valueT[primaryKey]+-
callback(node: T) => void--

Examples:

interface INodeItem {
  id: string;
  value: string;
  children?: INodeItem[];
}

const list: INodeItem[] = [
  {
    id: '0', // <- primary key
    value: 'v-0',
  },
  {
    id: '1',
    value: 'v-1',
    children: [ // <- children key
      {
        id: '1-1',
        value: 'v-1-1',
      },
    ],
  },
];

// Going through the list and finds a node with id === '1-1', returns a link to the found node
findByPrimaryKey('id', 'children')(list, '1-1'); -> { id: '1-1', value: 'v-1-1' }

const mutateCallback = (node: INodeItem) => node.value = 'mutated';

// Going through the list and finds a node with id === '1-1', calls mutateCallback on a found node, returns a link to the node
findByPrimaryKey('id', 'children')(
  list,
  '1-1',
  mutateCallback,
); -> { id: '1-1', value: 'mutated' }

Contributing

TODO: Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

License

ISC

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago