jackknife
    TypeScript icon, indicating that this package has built-in type declarations

    2.8.0 • Public • Published

    jackknife logo

    jackknife

    npm npm bundle size license Issues


    Description

    jackknife is a multi-tool that provides a set of utility functions to face the wild projects.
    All the blades are typescript compatible.


    Installation

    npm i jackknife

    In order to use any API you have to import them:

    // Typescript
    import { clone, getPassword, sort } from 'jackknife';
     
    // or Node
    const { clone, getPassword, sort } = require('jackknife');

    Browser support

    Latest versions of Chrome, Firefox, Opera, Safari, Edge and IE 9+ (*).

    * Notes for IE:

    • getQueue API require Promise support, so it doesn't work on all IE versions.
    • requestFullscreen and exitFullscreen API require Fullscreen support, available in IE 11 only.

    Test, Bugs and Feature requests

    If you want to execute unit test run:

    npm test

    For bugs and feature requests, please create an issue.


    API


    getCookie

    getCookie(name: string): string | null

    Get the value of a cookie.

    const token = getCookie('token');
    console.log(token); // cookie value
    

    setCookie

    setCookie(name: string, value: string, options: CookieOptions = {}): void

    Set the value of a cookie.

    setCookie('token', 'abc');

    CookieOptions are:

    class CookieOptions {
      expires?: Date;
      maxAge?: number;
      domain?: string;
      path?: string;
      secure?: boolean;
      httpOnly?: boolean;
      sameSite?: 'Strict' | 'Lax' | 'None';
    }
    

    For the details of CookieOptions see MDN reference.


    deleteCookie

    deleteCookie(name: string): void

    Delete a cookie.

    deleteCookie('token');

    random

    random(min: number, max: number, decimals = 0): number

    Generate a random number (integer or float) in the defined range.

    const randomInteger = random(5, 10);
    console.log(randomInteger); // i.e. 7
    
    const randomFloat = random(5, 10, 3);
    console.log(randomFloat); // i.e. 8.842
    

    round

    round(value: number, decimals = 2): number

    Round a number with the defined precision of decimals.

    const rounded = round(0.15666, 3);
    console.log(rounded); // 0.157
    

    unique

    unique(): number

    Generate an unique integer useful as an ID value.

    const uniqueInteger = unique();
    console.log(uniqueInteger); // 15764928947236012
    

    degToRad

    degToRad(degrees: number): number

    Convert degrees to radians.

    const radians = degToRad(180);
    console.log(radians); // PI value
    

    radToDeg

    radToDeg(radians: number): number

    Convert radians to degrees.

    const degrees = radToDeg(Math.PI);
    console.log(degrees); // 180
    

    chunks

    chunks<T>(array: T[], chunkSize: number): T[][]

    Split an array in a defined number of chunks.

    const array = ['a', 'b', 'c', 'd', 'e'];
    const arrayChunks = chunks<string>(array, 2);
    console.log(arrayChunks); // [['a', 'b'], ['c', 'd'], ['e']];
    

    sort

    sort<T>(array: T[], key: string, sortType: 'asc' | 'desc' = 'asc'): T[]

    Sort an array of objects by a defined object property.
    'key' can be a nested property (see getNested).

    interface TestItem { name: string; }
    const array: TestItem[] = [{ name: 'b' }, { name: 'c' }, { name: 'a' }];
    const sorted = sort<TestItem>(array, 'name');
    console.log(sorted); // [{ name: 'a' }, { name: 'b' }, { name: 'c' }];
    

    shuffle

    shuffle<T>(array: T[]): T[]

    Shuffle an array.

    const array = ['a', 'b', 'c', 'd', 'e'];
    const shuffled = shuffle<string>(array);
    console.log(shuffled); // i.e. ['b', 'd', 'c', 'a', 'e']
    

    range

    range(min: number, max: number): number[]

    Generate an array of numbers in a defined range.

    const array = range(8, 12);
    console.log(array); // [8, 9, 10, 11, 12]
    

    getCode

    getCode(length = 10, chars = 'all'): string

    Generate a random string.
    chars is the set of characters to use. It can be a predefined set between 'alphanumeric', 'letters', 'lower-letters', 'upper-letters', 'numbers', 'symbols', 'all' or a custom set.

    // Default
    console.log(getCode()); // i.e. 'nk3IGBPiOh'
    
    // Predefined set
    console.log(getCode(10, 'letters')); // i.e. 'LTaezrWFom'
    console.log(getCode(10, 'numbers')); // i.e. '9060379844'
    
    // Custom set
    console.log(getCode(10, 'abc123$%&')); // i.e. '12&%c222ac'
    

    getPassword

    getPassword(length = 10): string

    Generate a strong password. It mix up letters, numbers and symbols proportionally.
    length must be >= 6.

    const password = getPassword();
    console.log(password); // i.e. ';7hsE_%-77'
    

    getColor

    getColor(): string

    Generate a random color in hexadecimal notation.

    const color = getColor();
    console.log(color); // i.e. '#BC37D3'
    

    clone

    clone<T>(target: T, sameClass = true): T

    Clone an object and its nested content.
    If sameClass is true, the cloned object and its nested objects mantain the original class type instead of a generic 'Object' but it can create issues if the constructor of the objects to clone require any parameters.
    In this case set the sameClass option to false and the objects will be cloned only by their content, skipping the contructor and loosing the class type.

    const cloned = clone(myObject);
    console.log(cloned); // object cloned
    

    getNested

    getNested<T>(root: KeyValue<any>, path: string): T | null

    Get the nested value of a object property by a string path.

    const test = { a: { b: [{ c: 'banana' }] } };
    const nested = getNested<string>(test, 'a.b.0.c');
    console.log(nested); // 'banana'
    

    KeyValue

    interface KeyValue<T> { [key: string]: T; }

    An useful interface to cast the generic key-value objects.

    const stringCasted: KeyValue<string> = {
      some: 'string';
    };
    
    const choiceCasted: KeyValue<string | number> = {
      some: 'string',
      or: 2
    };
    
    const genericCasted: KeyValue<any> = {
      some: 'string',
      or: ...a mysterious thing
    };
    

    LabelValue

    interface LabelValue<T> { label: string; value: T; }

    An useful interface to cast the objects with the common label-value pair structure.

    const stringCasted: LabelValue<string> = {
      label: 'A label',
      value: 'A string';
    };
    
    const numberCasted: LabelValue<number> = {
      label: 'A label',
      value: 8;
    };
    
    const genericCasted: LabelValue<any> = {
      label: 'A label',
      value: ...a mysterious thing
    };
    

    getQuery

    getQuery(): { [key: string]: string }

    Get the query string of the current url.

    const query = getQuery();
    console.log(query); // i.e. { param: 'value' }
    

    getQueryParam

    getQueryParam(name: string): string | null

    Get a specific param of the current query string.

    const param = getQueryParam('param');
    console.log(param); // i.e. 'value'
    

    objToQuery

    objToQuery(target: KeyValue<any>): string

    Convert an object to a valid query string.

    const query = objToQuery({ param1: 'value 1', param2: 'value 2' );
    console.log(query); // 'param1=value%201¶m2=value%202'
    

    objToParams

    objToParams(target: KeyValue<any>, keepEmpty = false): KeyValue<string>

    Convert an object to another object with properties casted as valid GET param.
    This function can be useful with some frameworks (i.e. Angular) that require a KeyValue<string> objects as the params of HTTP GET request.
    The array values will be joined with the ','.
    The dates will be converted to ISO string.
    If the keepEmpty is true, the result maintain the empty values also like empty strings, pure objects (as empty string) and null values (as empty string). Otherwise they will be skipped.

    const object = {
      a: 'value',
      b: 2,
      c: new Date('2020-01-01'),
      d: [2, 3],
      e: {},
      f: null,
      g: ''
    };
    
    const params = objToParams(object);
    console.log(params);
    /*
      {
        a: 'value',
        b: '2',
        c: '2020-01-01T00:00:00.000Z',
        d: '2,3'
      }
    */
    
    const paramsWithEmpty = objToParams(object, true);
    console.log(paramsWithEmpty);
    /*
      {
        a: 'value',
        b: '2',
        c: '2020-01-01T00:00:00.000Z',
        d: '2,3',
        e: '',
        f: '',
        g: ''
      }
    */
    

    getQueue

    getQueue<T>(tasks: Array<() => Promise<T>>): Promise<T[]>

    Serialize and execute a list of Promises in the provided order.
    It return a Promise with the array of all ordered results.
    Note: 'tasks' is an array of functions that return a Promise.

    const tasks = [
      () => {
        return new Promise(resolve => {
          setTimeout(() => resolve(1), 100);
        });
      },
      () => new Promise(resolve => resolve(2)),
      () => new Promise(resolve => resolve(3))
    ];
    
    getQueue<number>(tasks)
      .then(results => console.log(results)); // [1, 2, 3]
    

    requestFullscreen

    requestFullscreen(element: HTMLElement): Promise<void>;

    Make the element be displayed in full-screen mode.
    This api is only a shortcut for all browser-specific 'requestFullscreen' (webkit, moz, ms).

    const element = document.getElementById('my-element');
    requestFullscreen(element);
    

    exitFullscreen

    exitFullscreen(): Promise<void>;

    Exit from the full-screen mode.
    This api is only a shortcut for all browser-specific 'exitFullscreen' (webkit, moz, ms).

    exitFullscreen();

    datetime

    datetime(date = new Date(), withTime = true): string

    Get the current date-time based on the local timezone. The format is "yyyy-mm-ddTHH:ii:ss+TZ".

    const now = datetime();
    console.log(now); // i.e. '2020-04-10T23:46:24+0200'
    

    pad

    pad(value: number | string, length: number, symbol: string): string

    Add a start padding to a value.

    const padded = pad(2, 4, '0');
    console.log(padded); // 0002
    

    Install

    npm i jackknife

    DownloadsWeekly Downloads

    2

    Version

    2.8.0

    License

    MIT

    Unpacked Size

    54.2 kB

    Total Files

    7

    Last publish

    Collaborators

    • zosma