Code Monkey home page Code Monkey logo

handilities's Introduction

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

Name Type Default value
target Object -

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

Name Type Default value
path string, string[] -
target Object -

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

Name Type Default value
path string[] -
target Object -

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

Name Type Required Default value
value number + -
options IBeautifyNumberOptions - { 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

Name Type Required Default value
initOptions IInitListUtilsOptions + -
IInitListUtilsOptions
Property Type Default value
primaryKey string -
childrenKey string -

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

Name Type Required Default value
primaryKey string + -
childrenKey string + -

Returns another function with the following arguments interface:

Name Type Required Default value
items (T extends Record<string, unknown>)[] + -
value T[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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.