Options
All
  • Public
  • Public/Protected
  • All
Menu

Module panacea-core

Index

Classes

Type aliases

Functions Algorithm

Functions Array

Functions Date

Functions Environment

Functions Event

Functions Function

Functions Math

Functions Object

Functions String

Functions Type

Type aliases

ColorizeRecord: { bgBlack: string; bgBlue: string; bgCyan: string; bgGreen: string; bgMagenta: string; bgRed: string; bgWhite: string; bgYellow: string; black: string; blue: string; cyan: string; green: string; magenta: string; red: string; white: string; yellow: string }

Type declaration

  • bgBlack: string
  • bgBlue: string
  • bgCyan: string
  • bgGreen: string
  • bgMagenta: string
  • bgRed: string
  • bgWhite: string
  • bgYellow: string
  • black: string
  • blue: string
  • cyan: string
  • green: string
  • magenta: string
  • red: string
  • white: string
  • yellow: string
LinkedListNode<T>: { next: LinkedListNode<T> | null; value: T }

Type parameters

  • T

Type declaration

Location: { latitude: number; longitude: number }

Object type representing latitude and longitude

Type declaration

  • latitude: number
  • longitude: number

Algorithm Functions

  • caesarCipher(str: string, shift: number, decrypt?: boolean): string
  • Encrypts or decrypts a given string using the Caesar cipher.

    example
    caesarCipher('Hello World!', -3); // 'Ebiil Tloia!'
    caesarCipher('Ebiil Tloia!', 23, true); // 'Hello World!'
    since

    0.1.1

    Parameters

    • str: string

      The string to encrypt or decrypt.

    • shift: number

      The amount of characters to shift.

    • decrypt: boolean = false

      Whether to decrypt or encrypt.

    Returns string

    The encrypted or decrypted string.

  • Calculate the distance

    example
    getDistance(
    { latitude: 34.23053, longitude: 108.93425 },
    { latitude: 40.22077, longitude: 116.23128 }
    )
    // => 928314
    since

    0.1.7

    Parameters

    Returns number

    distance in meters

Array Functions

  • JSONtoCSV(arr: {}[], columns: string[], delimiter?: string): string
  • Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

    example
    JSONtoCSV(
    [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],
    ['a', 'b']
    ); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
    JSONtoCSV(
    [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],
    ['a', 'b'],
    ';'
    ); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
    since

    0.1.3

    Parameters

    • arr: {}[]

      The array of objects to convert.

    • columns: string[]

      The columns to include in the CSV string.

    • delimiter: string = ","

      The delimiter to use between columns.

    Returns string

    The CSV string.

  • allEqual<T>(arr: T[]): boolean
  • Checks if all elements in an array are equal.

    example
    allEqual([1, 2, 3, 4, 5, 6]); // false
    allEqual([1, 1, 1, 1]); // true
    since

    0.1.5

    Type parameters

    • T: string | number

    Parameters

    • arr: T[]

      The array to check.

    Returns boolean

    True if all elements are equal, false otherwise.

  • allUnique(arr: any[]): boolean
  • Checks if all elements in an array are unique.

    example
    allUnique([1, 2, 3, 4]); // true
    allUnique([1, 1, 2, 3]); // false
    since

    0.1.11

    Parameters

    • arr: any[]

      The array to check.

    Returns boolean

    True if all elements are unique, false otherwise.

  • arrayToCSV(arr: (string | number)[][], delimiter?: string): string
  • Converts a 2D array to a comma-separated values (CSV) string.

    example
    arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
    arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
    arrayToCSV([['a', '"b" great'], ['c', 3.1415]]);
    // '"a","""b"" great"\n"c",3.1415'
    since

    0.1.10

    Parameters

    • arr: (string | number)[][]

      The array to convert.

    • delimiter: string = ","

      The delimiter to use.

    Returns string

    The CSV string.

  • compact(arr: any[]): any[]
  • Removes falsy values from an array.

    example
    compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
    // [ 1, 2, 3, 'a', 's', 34 ]
    since

    0.1.8

    Parameters

    • arr: any[]

      The array to compact.

    Returns any[]

    The compacted array.

  • countOccurrences<T>(arr: T[], val: T): number
  • Counts the occurrences of a value in an array.

    example
    countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
    
    since

    0.1.8

    Type parameters

    • T

    Parameters

    • arr: T[]

      The array to search.

    • val: T

      The value to search for.

    Returns number

    The number of occurrences of the value in the array.

  • everyNth(arr: any[], nth: number): any[]
  • Returns every nth element in an array.

    example
    everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
    
    since

    0.1.8

    Parameters

    • arr: any[]

      The array to process.

    • nth: number

      The nth element to return.

    Returns any[]

    The nth element in the array.

  • generateItems<T>(n: number, fn: (i: number) => T): T[]
  • Generates an array with the given amount of items, using the given function.

    example
    generateItems(10, Math.random);
    // [0.21, 0.08, 0.40, 0.96, 0.96, 0.24, 0.19, 0.96, 0.42, 0.70]
    since

    0.1.3

    Type parameters

    • T

    Parameters

    • n: number

      The amount of items to generate.

    • fn: (i: number) => T

      The function to use to generate the items.

        • (i: number): T
        • Parameters

          • i: number

          Returns T

    Returns T[]

    The generated array.

  • hasDuplicates<T>(arr: T[]): boolean
  • Checks if there are duplicate values in a flat array.

    example
    hasDuplicates([0, 1, 1, 2]); // true
    hasDuplicates([0, 1, 2, 3]); // false
    since

    0.1.5

    Type parameters

    • T: string | number

    Parameters

    • arr: T[]

      The array to check.

    Returns boolean

    True if there are duplicate values, false otherwise.

  • head(arr: any[]): any
  • Returns the head of an array.

    example
    head([1, 2, 3]); // 1
    head([]); // undefined
    head(null); // undefined
    head(undefined); // undefined
    since

    0.1.4

    Parameters

    • arr: any[]

      The array to get the head of.

    Returns any

    The head of the array.

  • includesAll(arr: any[], values: any[]): boolean
  • Checks if all the elements in values are included in arr.

    example
    includesAll([1, 2, 3, 4], [1, 4]); // true
    includesAll([1, 2, 3, 4], [1, 5]); // false
    since

    0.1.5

    Parameters

    • arr: any[]

      The array to check.

    • values: any[]

      The values to check for.

    Returns boolean

    true if all the elements in values are included in arr.

  • includesAny(arr: any[], values: any[]): boolean
  • Checks if at least one element of values is included in arr.

    example
    includesAny([1, 2, 3, 4], [2, 9]); // true
    includesAny([1, 2, 3, 4], [8, 9]); // false
    since

    0.1.5

    Parameters

    • arr: any[]

      The array to check.

    • values: any[]

      The values to check for.

    Returns boolean

    true if at least one value is included in arr, otherwise false.

  • initial(arr: any[]): any[]
  • Returns all the elements of an array except the last one.

    example
    initial([1, 2, 3]); // [1, 2]
    
    since

    0.1.5

    Parameters

    • arr: any[]

      The array to process.

    Returns any[]

    The array with the last element removed.

  • initialize2DArray(w: number, h: number, val?: any): any[][]
  • Initializes a 2D array of given width and height and value.

    example
    initialize2DArray(2, 2, 0); // [[0, 0], [0, 0]]
    
    since

    0.1.8

    Parameters

    • w: number

      Width of the array.

    • h: number

      Height of the array.

    • val: any = null

      Value to initialize the array with.

    Returns any[][]

    A 2D array of given width and height and value.

  • initializeArrayWithValues(n: number, val?: any): any[]
  • Initializes and fills an array with the specified values.

    example
    initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]
    
    since

    0.1.4

    Parameters

    • n: number

      The length of the array.

    • val: any = 0

      The value to fill the array with.

    Returns any[]

    The array.

  • intersection(a: (string | number | boolean)[], b: (string | number | boolean)[]): (string | number | boolean)[]
  • Returns the elements that exist in both arrays, filtering duplicate values.

    example
    intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
    
    since

    0.1.8

    Parameters

    • a: (string | number | boolean)[]

      First array.

    • b: (string | number | boolean)[]

      Second array.

    Returns (string | number | boolean)[]

    An array of elements in both a and b.

  • isSorted(arr: number[]): number
  • Checks if a numeric array is sorted.

    example
    isSorted([0, 1, 2, 2]); // 1
    isSorted([4, 3, 2]); // -1
    isSorted([4, 3, 5]); // 0
    isSorted([4]); // 0
    since

    0.1.5

    Parameters

    • arr: number[]

      The array to check.

    Returns number

    1 if the array is ascending order, -1 if the array is descending order, 0 otherwise.

  • last(arr: any[]): any
  • Returns the last element in an array.

    example
    last([1, 2, 3]); // 3
    last([]); // undefined
    last(null); // undefined
    last(undefined); // undefined
    since

    0.1.5

    Parameters

    • arr: any[]

      The array to query.

    Returns any

    The last element in the array.

  • nthElement(arr: any[], n?: number): any
  • Returns the nth element of an array.

    example
    nthElement(['a', 'b', 'c'], 1); // 'b'
    nthElement(['a', 'b', 'b'], -3); // 'a'
    since

    0.1.8

    Parameters

    • arr: any[]

      The array to get the element from.

    • n: number = 0

      The index of the element to get.

    Returns any

    The nth element of the array.

  • sample(arr: any[]): any
  • Gets a random element from an array.

    example
    sample([3, 7, 9, 11]); // 9
    
    since

    0.1.10

    Parameters

    • arr: any[]

      The array to sample from.

    Returns any

    A random element from the array.

  • similarity<T>(arr: T[], values: T[]): T[]
  • Returns an array of elements that appear in both arrays.

    example
    similarity([1, 2, 3], [1, 2, 4]); // [1, 2]
    
    since

    0.1.8

    Type parameters

    • T

    Parameters

    • arr: T[]

      The first array.

    • values: T[]

      The second array.

    Returns T[]

    An array of elements that appear in both arrays.

  • sortedIndex(arr: number[], n: number): number
  • Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting order.

    example
    sortedIndex([5, 3, 2, 1], 4); // 1
    sortedIndex([30, 50], 40); // 1
    since

    0.1.8

    Parameters

    • arr: number[]

      The sorted array to inspect.

    • n: number

      The value to evaluate.

    Returns number

    The lowest index at which n should be inserted into arr in order to maintain the sort order.

  • sortedLastIndex(arr: number[], n: number): number
  • Finds the highest index at which a value should be inserted into an array in order to maintain its sort order.

    example
    sortedLastIndex([10, 20, 30, 30, 40], 30); // 4
    
    since

    0.1.8

    Parameters

    • arr: number[]

      The array to inspect.

    • n: number

      The value to evaluate.

    Returns number

    Returns the index at which value should be inserted into array in order to maintain its sort order.

  • subSet(a: Iterable<string | number>, b: Iterable<string | number>): boolean
  • Checks if the first iterable is a subset of the second one, excluding duplicate values.

    example
    subSet(new Set([1, 2]), new Set([1, 2, 3, 4])); // true
    subSet(new Set([1, 5]), new Set([1, 2, 3, 4])); // false
    since

    0.1.8

    Parameters

    • a: Iterable<string | number>

      The first iterable.

    • b: Iterable<string | number>

      The second iterable.

    Returns boolean

    true if the first iterable is a subset of the second one, excluding duplicate values.

  • superSet(a: Iterable<string | number>, b: Iterable<string | number>): boolean
  • Checks if the first iterable is a superset of the second one, excluding duplicate values.

    example
    superSet(new Set([1, 2, 3, 4]), new Set([1, 2])); // true
    superSet(new Set([1, 2, 3, 4]), new Set([1, 5])); // false
    since

    0.1.8

    Parameters

    • a: Iterable<string | number>

      The first iterable.

    • b: Iterable<string | number>

      The second iterable.

    Returns boolean

    true if the first iterable is a superset of the second one, excluding duplicate values.

  • tail(arr: any[]): any[]
  • Returns all elements in an array except for the first one.

    example
    tail([1, 2, 3]); // [2, 3]
    tail([1]); // [1]
    tail([]); // []
    since

    0.1.5

    Parameters

    • arr: any[]

      The array to return the tail of.

    Returns any[]

    The tail of the array.

  • union(a: any[], b: any[]): any[]
  • Returns every element that exists in any of the two arrays at least once.

    example
    union([1, 2, 3], [4, 3, 2]); // [1, 2, 3, 4]
    
    since

    0.1.1

    Parameters

    • a: any[]

      The first array.

    • b: any[]

      The second array.

    Returns any[]

    The union of the two arrays.

  • uniqueElements<T>(arr: T[]): T[]
  • Finds all unique values in an array.

    example
    uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
    
    since

    0.1.5

    Type parameters

    • T: string | number

    Parameters

    • arr: T[]

      The array to find unique values in.

    Returns T[]

    An array of unique values.

  • without(arr: (string | number | boolean)[], ...args: (string | number | boolean)[]): (string | number | boolean)[]
  • Filters out the elements of an array that have one of the specified values.

    example
    without([2, 1, 2, 3], 1, 2); // [3]
    
    since

    0.1.8

    Parameters

    • arr: (string | number | boolean)[]

      The array to filter.

    • Rest ...args: (string | number | boolean)[]

      The values to exclude.

    Returns (string | number | boolean)[]

    The filtered array.

Date Functions

  • addDaysToDate(date: string, n: number): string
  • Calculates the date of n days from the given date, returning its string representation.

    example
    addDaysToDate('2020-10-15', 10); // '2020-10-25'
    addDaysToDate('2020-10-15', -10); // '2020-10-05'
    since

    0.1.13

    Parameters

    • date: string

      The date to add days to.

    • n: number

      The number of days to add.

    Returns string

    The date of n days from the given date, as a string.

  • addMinutesToDate(date: string | number | Date, n: number): Date
  • Calculates the date of n minutes from the given date, returning its string representation.

    example
    addMinutesToDate('2020-10-19 12:00:00', 10); // new Date('2020-10-19 12:10:00')
    addMinutesToDate('2020-10-19', -10).toUTCString() === 'Sun, 18 Oct 2020 23:50:00 GMT'
    since

    0.0.14

    Parameters

    • date: string | number | Date

      The date to add minutes to.

    • n: number

      The number of minutes to add.

    Returns Date

    The date of n minutes from the given date, as a string.

  • addWeekDays(startDate: Date, count: number): Date
  • Calculates the date after adding the given number of business days.

    example
    addWeekDays(new Date('Oct 09, 2020'), 5); // 'Oct 16, 2020'
    addWeekDays(new Date('Oct 12, 2020'), 5); // 'Oct 19, 2020'
    since

    0.1.14

    Parameters

    • startDate: Date

      The date to start with.

    • count: number

      The number of business days to add.

    Returns Date

    The new date.

  • countWeekDaysBetween(startDate: Date, endDate: Date): number
  • Counts the weekdays between two dates.

    example
    countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 06, 2020')); // 1
    countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 14, 2020')); // 7
    since

    0.1.14

    Parameters

    • startDate: Date

      The start date.

    • endDate: Date

      The end date.

    Returns number

    The number of weekdays between the two dates.

  • dateRangeGenerator(start: Date, end: Date, step?: number): Generator<Date>
  • Creates a generator, that generates all dates in the given range using the given step.

    example
    [...dateRangeGenerator(new Date('2021-06-01'), new Date('2021-06-04'))];
    // [ 2021-06-01, 2021-06-02, 2021-06-03 ]
    since

    0.1.14

    Parameters

    • start: Date

      The start date of the range.

    • end: Date

      The end date of the range.

    • step: number = 1

      The step.

    Returns Generator<Date>

    The generator.

  • dayName(date: Date, locale?: string): string
  • Gets the name of the weekday from a Date object.

    example
    dayName(new Date()); // 'Saturday'
    dayName(new Date('09/23/2020'), 'de-DE'); // 'Samstag'
    since

    0.1.11

    Parameters

    • date: Date

      The Date object.

    • Optional locale: string

      The locale to use.

    Returns string

    The name of the weekday.

  • dayOfYear(date: Date): number
  • Gets the day of the year (number in the range 1-366) from a Date object.

    example
    dayOfYear(new Date(2022, 0, 1)); // 1
    dayOfYear(new Date(2022, 11, 31)); // 365
    since

    0.1.13

    Parameters

    • date: Date

      The Date object to get the day of the year from.

    Returns number

    The day of the year.

  • daysAgo(n: number): string
  • Calculates the date of n days ago from today as a string representation.

    example
    daysAgo(20); // 2020-09-16 (if current date is 2020-10-06)
    
    since

    0.1.11

    Parameters

    • n: number

      The number of days ago.

    Returns string

    The date of n days ago as a string representation.

  • daysFromNow(n: number): string
  • Calculates the date of n days from today as a string representation.

    example
    daysFromNow(5); // 2020-10-13 (if current date is 2020-10-08)
    
    since

    0.1.11

    Parameters

    • n: number

      The number of days from today.

    Returns string

    The date of n days from today as a string representation.

  • daysInMonth(year: number, month: number): number
  • Gets the number of days in the given month of the specified year.

    example
    daysInMonth(2020, 12)); // 31
    daysInMonth(2024, 2)); // 29
    since

    0.1.8

    Parameters

    • year: number

      The year.

    • month: number

      The month.

    Returns number

    The number of days in the month.

  • formatDuration(ms: number): string
  • Returns the human-readable format of the given number of milliseconds.

    example
    formatDuration(1001); // '1 second, 1 millisecond'
    formatDuration(34325055574);
    // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
    since

    0.1.14

    Parameters

    • ms: number

      The number of milliseconds.

    Returns string

    The human-readable format of the given number of milliseconds.

  • formatSeconds(s: number): string
  • Returns the ISO format of the given number of seconds.

    example
    formatSeconds(200); // '00:03:20'
    formatSeconds(-200); // '-00:03:20'
    formatSeconds(99999); // '27:46:39'
    since

    0.1.14

    Parameters

    • s: number

      The number of seconds.

    Returns string

    The ISO format of the given number of seconds.

  • fromTimestamp(timestamp: number): Date
  • Creates a Date object from a Unix timestamp.

    example
    fromTimestamp(1602162242); // 2020-10-08T13:04:02.000Z
    
    since

    0.1.8

    Parameters

    • timestamp: number

      The Unix timestamp.

    Returns Date

    The Date object.

  • getColonTimeFromDate(date: Date): string
  • Returns a string of the form HH:MM:SS from a Date object.

    example
    getColonTimeFromDate(new Date()); // '08:38:00'
    
    since

    0.1.10

    Parameters

    • date: Date

      The Date object to get the time from.

    Returns string

    The time as a string.

  • getDaysDiffBetweenDates(dateInitial: Date, dateFinal: Date): number
  • Calculates the difference (in days) between two dates.

    example
    getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22'));
    // 9
    since

    0.1.9

    Parameters

    • dateInitial: Date

      The first date.

    • dateFinal: Date

      The second date.

    Returns number

    The difference (in days) between the two dates.

  • getHoursDiffBetweenDates(dateInitial: Date, dateFinal: Date): number
  • Calculates the difference (in hours) between two dates.

    example
    getHoursDiffBetweenDates(
    new Date('2021-04-24 10:25:00'),
    new Date('2021-04-25 10:25:00')
    ); // 24
    since

    0.1.9

    Parameters

    • dateInitial: Date

      The first date.

    • dateFinal: Date

      The second date.

    Returns number

    The difference (in hours) between the two dates.

  • getMeridiemSuffixOfInteger(num: number): string
  • Converts an integer to a suffixed string, adding am or pm based on its value.

    example
    getMeridiemSuffixOfInteger(0); // '12am'
    getMeridiemSuffixOfInteger(11); // '11am'
    getMeridiemSuffixOfInteger(13); // '1pm'
    getMeridiemSuffixOfInteger(25); // '1pm'
    since

    0.1.9

    Parameters

    • num: number

      The number to convert.

    Returns string

    The suffixed string.

  • getMinutesDiffBetweenDates(dateInitial: Date, dateFinal: Date): number
  • Calculates the difference (in minutes) between two dates.

    example
    getMinutesDiffBetweenDates(
    new Date('2021-04-24 01:00:15'),
    new Date('2021-04-24 02:00:15')
    ); // 60
    since

    0.1.9

    Parameters

    • dateInitial: Date

      The first date.

    • dateFinal: Date

      The second date.

    Returns number

    The difference (in minutes) between the two dates.

  • getMonthsDiffBetweenDates(dateInitial: Date, dateFinal: Date): number
  • Calculates the difference (in months) between two dates.

    example
    getMonthsDiffBetweenDates(new Date('2017-12-13'), new Date('2018-04-29')); // 4
    
    since

    0.1.9

    Parameters

    • dateInitial: Date

      The initial date.

    • dateFinal: Date

      The final date.

    Returns number

    The difference (in months) between the two dates.

  • getSecondsDiffBetweenDates(dateInitial: Date, dateFinal: Date): number
  • Calculates the difference (in seconds) between two dates.

    example
    getSecondsDiffBetweenDates(
    new Date('2020-12-24 00:00:15'),
    new Date('2020-12-24 00:00:17')
    ); // 2
    since

    0.1.9

    Parameters

    • dateInitial: Date

      The first date.

    • dateFinal: Date

      The second date.

    Returns number

    The difference (in seconds) between the two dates.

  • getTimestamp(date?: Date): number
  • Gets the Unix timestamp from a Date object.

    example
    getTimestamp(); // 1602162242
    
    since

    0.1.9

    Parameters

    • date: Date = ...

      The Date object to get the timestamp from.

    Returns number

    The Unix timestamp.

  • isAfterDate(dateA: Date, dateB: Date): boolean
  • Checks if a date is after another date.

    example
    isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
    
    since

    0.1.4

    Parameters

    • dateA: Date

      The first date to compare.

    • dateB: Date

      The second date to compare.

    Returns boolean

    true if dateA is after dateB, false otherwise.

  • isBeforeDate(dateA: Date, dateB: Date): boolean
  • Checks if a date is before another date.

    example
    isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
    
    since

    0.1.4

    Parameters

    • dateA: Date

      The first date to compare.

    • dateB: Date

      The second date to compare.

    Returns boolean

    true if dateA is before dateB, false otherwise.

  • isBetweenDates(dateStart: Date, dateEnd: Date, date: Date): boolean
  • Checks if a date is between two other dates.

    example
    isBetweenDates(
    new Date(2010, 11, 20),
    new Date(2010, 11, 30),
    new Date(2010, 11, 19)
    ); // false
    isBetweenDates(
    new Date(2010, 11, 20),
    new Date(2010, 11, 30),
    new Date(2010, 11, 25)
    ); // true
    since

    0.1.1

    Parameters

    • dateStart: Date

      The start date.

    • dateEnd: Date

      The end date.

    • date: Date

      The date to check.

    Returns boolean

    True if the date is between the start and end dates.

  • isDateValid(...val: any[]): boolean
  • Checks if a valid date object can be created from the given values.

    example
    isDateValid('December 17, 1995 03:24:00'); // true
    isDateValid('1995-12-17T03:24:00'); // true
    isDateValid('1995-12-17 T03:24:00'); // false
    isDateValid('Duck'); // false
    isDateValid(1995, 11, 17); // true
    isDateValid(1995, 11, 17, 'Duck'); // false
    isDateValid({}); // false
    since

    0.1.14

    Parameters

    • Rest ...val: any[]

      the value to check

    Returns boolean

    true if the date is valid, false otherwise

  • isISOString(val: string): boolean
  • Checks if the given string is valid in the simplified extended ISO format (ISO 8601).

    example
    isISOString('2020-10-12T10:10:10.000Z'); // true
    isISOString('2020-10-12'); // false
    since

    0.1.11

    Parameters

    • val: string

      The string to check.

    Returns boolean

    True if the string is valid, false otherwise.

  • isLeapYear(year: number): boolean
  • Checks if the given year is a leap year.

    example
    isLeapYear(2019); // false
    isLeapYear(2020); // true
    since

    0.1.8

    Parameters

    • year: number

      The year to check.

    Returns boolean

    true if the given year is a leap year, otherwise false.

  • isSameDate(dateA: Date, dateB: Date): boolean
  • Checks if a date is the same as another date.

    example
    isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
    isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // false
    since

    0.1.8

    Parameters

    • dateA: Date

      The first date to check.

    • dateB: Date

      The second date to check.

    Returns boolean

    True if the dates are the same, false otherwise.

  • isWeekday(d?: Date): boolean
  • Checks if the given date is a weekday.

    example
    isWeekday(); // true (if current date is 2019-07-19)
    isWeekday(new Date(2019, 6, 19)); // true
    since

    0.1.8

    Parameters

    • d: Date = ...

      The date to check.

    Returns boolean

    True if the given date is a weekday, false otherwise.

  • isWeekend(d?: Date): boolean
  • Checks if the given date is a weekend.

    example
    isWeekend(); // 2018-10-19 (if current date is 2018-10-18)
    
    since

    0.1.8

    Parameters

    • d: Date = ...

      The date to check.

    Returns boolean

    True if the given date is a weekend, false otherwise.

  • lastDateOfMonth(date?: Date): string
  • Returns the string representation of the last date in the given date's month.

    example
    lastDateOfMonth(new Date('2015-08-11')); // '2015-08-30'
    
    since

    0.1.8

    Parameters

    • date: Date = ...

      The date to get the last date of.

    Returns string

    The last date in the given date's month.

  • maxDate(...dates: Date[]): Date
  • Returns the maximum of the given dates.

    example
    const dates = [
    new Date(2017, 4, 13),
    new Date(2018, 2, 12),
    new Date(2016, 0, 10),
    new Date(2016, 0, 9)
    ];
    maxDate(...dates); // 2018-03-11T22:00:00.000Z
    since

    0.1.11

    Parameters

    • Rest ...dates: Date[]

      The dates to compare.

    Returns Date

    The maximum date.

  • minDate(...dates: Date[]): Date
  • Returns the minimum of the given dates.

    example
    const dates = [
    new Date(2017, 4, 13),
    new Date(2018, 2, 12),
    new Date(2016, 0, 10),
    new Date(2016, 0, 9)
    ];
    minDate(...dates); // 2016-01-08T22:00:00.000Z
    since

    0.1.11

    Parameters

    • Rest ...dates: Date[]

      The dates to compare.

    Returns Date

    The minimum date.

  • quarterOfYear(date?: Date): number[]
  • Returns the quarter and year to which the supplied date belongs to.

    example
    quarterOfYear(new Date('07/10/2018')); // [ 3, 2018 ]
    quarterOfYear(); // [ 2, 2022 ]
    since

    0.1.13

    Parameters

    • date: Date = ...

      The date to check.

    Returns number[]

    The quarter and year to which the supplied date belongs to.

  • toISOStringWithTimezone(date: Date): string
  • Converts a date to extended ISO format (ISO 8601), including timezone offset.

    example
    toISOStringWithTimezone(new Date()); // '2022-05-14T21:47:13+08:00'
    
    since

    0.1.14

    Parameters

    • date: Date

      Date to convert.

    Returns string

    Extended ISO format string.

  • tomorrow(): string
  • Results in a string representation of tomorrow's date.

    example
    tomorrow(); // 2018-10-19 (if current date is 2018-10-18)
    
    since

    0.1.9

    Returns string

    Tomorrow's date.

  • weekOfYear(date: Date): number
  • Returns the zero-indexed week of the year that a date corresponds to.

    example
    weekOfYear(new Date('2022-05-08')); // 17
    
    since

    0.1.11

    Parameters

    • date: Date

      The date to get the week of.

    Returns number

    The week of the year.

  • yesterday(): string
  • Results in a string representation of yesterday's date.

    example
    yesterday(); // 2018-10-17 (if current date is 2018-10-18)
    
    since

    0.1.9

    Returns string

Environment Functions

  • isBrowser(): boolean
  • Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

    example
    isBrowser(); // true (browser)
    isBrowser(); // false (Node)
    since

    0.1.0

    Returns boolean

  • isNode(): boolean
  • Determines if the current runtime environment is Node.js.

    example
    isNode(); // true (Node)
    isNode(); // false (browser)
    since

    0.1.0

    Returns boolean

Event Functions

  • createEventHub(): { hub: any; emit: any; off: any; on: any }
  • Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.

    example
    const handler = data => console.log(data);
    const hub = createEventHub();
    let increment = 0;

    // Subscribe: listen for different types of events
    hub.on('message', handler);
    hub.on('message', () => console.log('Message event fired'));
    hub.on('increment', () => increment++);

    // Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument
    hub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'
    hub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'
    hub.emit('increment'); // `increment` variable is now 1

    // Unsubscribe: stop a specific handler from listening to the 'message' event
    hub.off('message', handler);
    since

    0.1.7

    Returns { hub: any; emit: any; off: any; on: any }

    EventHub

    • hub: any
    • emit:function
      • emit(event: string, data?: any): void
    • off:function
      • off(event: string, handler: (data: any) => void): void
    • on:function
      • on(event: string, handler: (data: any) => void): void

Function Functions

  • coalesceFactory(valid: (v: any) => boolean): (...args: any[]) => any
  • Customizes a coalesce function that returns the first argument which is true based on the given validator.

    example
    const customCoalesce = coalesceFactory(
    v => ![null, undefined, '', NaN].includes(v)
    );
    customCoalesce(undefined, null, NaN, '', 'Waldo'); // 'Waldo'
    since

    0.1.0

    Parameters

    • valid: (v: any) => boolean

      A validator function that returns true if the argument is valid.

        • (v: any): boolean
        • Parameters

          • v: any

          Returns boolean

    Returns (...args: any[]) => any

    A coalesce function that returns the first argument which is true based on the given validator.

      • (...args: any[]): any
      • Parameters

        • Rest ...args: any[]

        Returns any

  • collectInto(fn: (args: any[]) => any): (...args: any[]) => any
  • Changes a function that accepts an array into a variadic function.

    example
    const Pall = collectInto(Promise.all.bind(Promise));
    let p1 = Promise.resolve(1);
    let p2 = Promise.resolve(2);
    let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
    Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
    since

    0.1.8

    Parameters

    • fn: (args: any[]) => any

      The function to convert.

        • (args: any[]): any
        • Parameters

          • args: any[]

          Returns any

    Returns (...args: any[]) => any

    A variadic function.

      • (...args: any[]): any
      • Parameters

        • Rest ...args: any[]

        Returns any

  • either(f: (...args: any) => boolean, g: (...args: any) => boolean): (...args: any) => boolean
  • Checks if at least one function returns true for a given set of arguments.

    example
    const isEven = num => num % 2 === 0;
    const isPositive = num => num > 0;
    const isPositiveOrEven = either(isPositive, isEven);
    isPositiveOrEven(4); // true
    isPositiveOrEven(3); // true
    since

    0.1.9

    Parameters

    • f: (...args: any) => boolean

      The functions to check.

        • (...args: any): boolean
        • Parameters

          • Rest ...args: any

          Returns boolean

    • g: (...args: any) => boolean

      The arguments to check.

        • (...args: any): boolean
        • Parameters

          • Rest ...args: any

          Returns boolean

    Returns (...args: any) => boolean

    true if at least one function returns true for the given arguments.

      • (...args: any): boolean
      • Parameters

        • Rest ...args: any

        Returns boolean

  • negate(func: (...args: any) => boolean): (...args: any) => boolean
  • Negates a predicate function.

    example
    [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
    
    since

    0.1.9

    Parameters

    • func: (...args: any) => boolean

      The predicate function to negate.

        • (...args: any): boolean
        • Parameters

          • Rest ...args: any

          Returns boolean

    Returns (...args: any) => boolean

    A negated predicate function.

      • (...args: any): boolean
      • Parameters

        • Rest ...args: any

        Returns boolean

  • timeTaken(callback: () => any): any
  • Measures the time it takes for a function to execute.

    example
    timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
    
    since

    0.1.9

    Parameters

    • callback: () => any

      The function to measure.

        • (): any
        • Returns any

    Returns any

    The result of the function.

  • unary(fn: (arg: any) => any): any
  • Creates a function that accepts up to one argument, ignoring any additional arguments.

    example
    ['1', '2', '3'].map(unary(parseInt)); // [1, 2, 3]
    
    since

    0.1.4

    Parameters

    • fn: (arg: any) => any

      The function to wrap.

        • (arg: any): any
        • Parameters

          • arg: any

          Returns any

    Returns any

    A function that will only accept one argument.

  • when(pred: (x: any) => boolean, whenTrue: (x: any) => any): (x: any) => any
  • Returns a function that takes one argument and runs a callback if it's truthy or returns it if falsy.

    example
    const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2);
    doubleEvenNumbers(2); // 4
    doubleEvenNumbers(1); // 1
    since

    0.1.3

    Parameters

    • pred: (x: any) => boolean

      A predicate function.

        • (x: any): boolean
        • Parameters

          • x: any

          Returns boolean

    • whenTrue: (x: any) => any

      A callback function to run if the predicate is truthy.

        • (x: any): any
        • Parameters

          • x: any

          Returns any

    Returns (x: any) => any

    A function that takes one argument and runs a callback if it's truthy or returns it if falsy.

      • (x: any): any
      • Parameters

        • x: any

        Returns any

Math Functions

  • approximatelyEqual(v1: number, v2: number, epsilon?: number): boolean
  • Checks if two numbers are approximately equal to each other.

    example
    approximatelyEqual(Math.PI / 2.0, 1.5708); // true
    approximatelyEqual(Math.PI / 2.0, 1.5708, 0.000001); // false
    since

    0.1.12

    Parameters

    • v1: number

      First number.

    • v2: number

      Second number.

    • epsilon: number = 0.001

      Tolerance.

    Returns boolean

    True if the numbers are approximately equal, false otherwise.

  • average(...nums: number[]): number
  • Calculates the average of two or more numbers.

    example
    average(...[1, 2, 3]); // 2
    average(1, 2, 3); // 2
    since

    0.1.11

    Parameters

    • Rest ...nums: number[]

      The numbers to average.

    Returns number

    The average of the numbers.

  • clampNumber(num: number, a: number, b: number): number
  • Clamps num within the inclusive range specified by the boundary values a and b.

    example
    clampNumber(2, 3, 5); // 3
    clampNumber(1, -1, -5); // -1
    since

    0.1.15

    Parameters

    • num: number

      The number to clamp.

    • a: number

      The first boundary value.

    • b: number

      The second boundary value.

    Returns number

    The clamped number.

  • copySign(x: number, y: number): number
  • Copy sign to number Returns the absolute value of the first number, but the sign of the second.

    example
    copySign(2, 3); // 2
    copySign(2, -3); // -2
    copySign(-2, 3); // 2
    copySign(-2, -3); // -2
    since

    0.1.15

    Parameters

    • x: number

      The number to take the absolute value of.

    • y: number

      The sign of the number.

    Returns number

    The absolute value of the first number, but the sign of the second.

  • degreesToRads(deg: number): number
  • Converts an angle from degrees to radians.

    example
    degreesToRads(90.0); // ~1.5708
    
    since

    0.1.9

    Parameters

    • deg: number

      The angle in degrees.

    Returns number

    The angle in radians.

  • distance(x0: number, y0: number, x1: number, y1: number): number
  • Calculates the distance between two points.

    example
    distance(1, 1, 2, 3); // ~2.2361
    
    since

    0.1.15

    Parameters

    • x0: number

      The x coordinate of the first point.

    • y0: number

      The y coordinate of the first point.

    • x1: number

      The x coordinate of the second point.

    • y1: number

      The y coordinate of the second point.

    Returns number

    The distance between the two points.

  • hasDecimals(num: number): boolean
  • Checks if a number has any decimals digits

    example
    hasDecimals(1); // false
    hasDecimals(1.001); // true
    since

    0.1.14

    Parameters

    • num: number

      number to check

    Returns boolean

    true if the number has decimals

  • inRange(n: number, start: number, end?: number): boolean
  • Checks if the given number falls within the given range.

    example
    inRange(3, 2, 5); // true
    inRange(3, 4); // true
    inRange(2, 3, 5); // false
    inRange(3, 2); // false
    since

    0.1.15

    Parameters

    • n: number

      The number to check.

    • start: number

      The start of the range.

    • Optional end: number

      The end of the range.

    Returns boolean

    true if the number is within the range, otherwise false.

  • isDivisible(dividend: number, divisor: number): boolean
  • Checks if the first numeric argument is divisible by the second one.

    example
    isDivisible(3, 2); // false
    isDivisible(6, 2); // true
    since

    0.1.12

    Parameters

    • dividend: number

      The dividend.

    • divisor: number

      The divisor.

    Returns boolean

    True if the dividend is divisible by the divisor, false otherwise.

  • isEven(num: number): boolean
  • Checks if the given number is even.

    example
    isEven(2); // true
    isEven(3); // false
    since

    0.1.12

    Parameters

    • num: number

      The number to check.

    Returns boolean

    True if the number is even, false otherwise.

  • isNegativeZero(val: number): boolean
  • Checks if the given value is equal to negative zero (-0).

    example
    isNegativeZero(-0); // true
    isNegativeZero(0); // false
    since

    0.1.12

    Parameters

    • val: number

      The value to check.

    Returns boolean

    true if the value is negative zero, otherwise false.

  • isOdd(num: number): boolean
  • Checks if the given number is odd.

    example
    isOdd(3); // true
    isOdd(2); // false
    since

    0.1.12

    Parameters

    • num: number

      The number to check.

    Returns boolean

    True if the number is odd, false otherwise.

  • isPowerOfTen(n: number): boolean
  • Checks if the given number is a power of 10.

    example
    isPowerOfTen(1); // true
    isPowerOfTen(10); // true
    isPowerOfTen(20); // false
    since

    0.1.11

    Parameters

    • n: number

      The number to check.

    Returns boolean

    True if the number is a power of 10, false otherwise.

  • isPowerOfTwo(n: number): boolean
  • Checks if the given number is a power of 2.

    example
    isPowerOfTwo(0); // false
    isPowerOfTwo(1); // true
    isPowerOfTwo(8); // true
    since

    0.1.11

    Parameters

    • n: number

      The number to check.

    Returns boolean

    True if the number is a power of 2, false otherwise.

  • isPrime(num: number): boolean
  • Checks if the provided integer is a prime number.

    example
    isPrime(11); // true
    isPrime(12); // false
    since

    0.1.4

    Parameters

    • num: number

      The number to check.

    Returns boolean

    True if the number is prime, false otherwise.

  • logBase(n: number, base: number): number
  • Calculates the logarithm of the given number in the given base.

    example
    logBase(10, 10); // 1
    logBase(100, 10); // 2
    since

    0.1.15

    Parameters

    • n: number

      The number.

    • base: number

      The base.

    Returns number

    The logarithm of the given number in the given base.

  • median(arr: number[]): number
  • Calculates the median of an array of numbers.

    example
    median([5, 6, 50, 1, -5]); // 5
    
    since

    0.1.8

    Parameters

    • arr: number[]

      The array of numbers.

    Returns number

    The median of the array.

  • nthRoot(x: number, n: number): number
  • Calculates the nth root of a given number.

    example
    nthRoot(32, 5); // 2
    
    since

    0.1.8

    Parameters

    • x: number

      The number for which to calculate the nth root.

    • n: number

      The root.

    Returns number

    The nth root of x.

  • prod(...arr: number[]): number
  • Calculates the product of two or more numbers/arrays.

    example
    prod(1, 2, 3, 4); // 24
    prod(...[1, 2, 3, 4]); // 24
    since

    0.1.8

    Parameters

    • Rest ...arr: number[]

      The array of numbers to multiply.

    Returns number

    The product of all the numbers in the array.

  • radsToDegrees(rad: number): number
  • Converts an angle from radians to degrees.

    example
    radsToDegrees(Math.PI / 2); // 90
    
    since

    0.1.9

    Parameters

    • rad: number

      The angle in radians.

    Returns number

    The angle in degrees.

  • round(n: number, decimals?: number): number
  • Rounds a number to a specified amount of digits.

    example
    round(1.005, 2); // 1.01
    round(1.005, 3); // 1.005
    round(1.005); // 1
    since

    0.1.15

    Parameters

    • n: number

      The number to round.

    • decimals: number = 0

      The amount of decimals to round to.

    Returns number

    The rounded number.

  • sum(...arr: number[]): number
  • Calculates the sum of two or more numbers/arrays.

    example
    sum(1, 2, 3, 4); // 10
    sum(...[1, 2, 3, 4]); // 10
    since

    0.1.8

    Parameters

    • Rest ...arr: number[]

      The array of numbers to sum.

    Returns number

    The sum of the numbers in the array.

  • sumN(n: number): number
  • Sums all the numbers between 1 and n.

    example
    sumN(100); // 5050
    
    since

    0.1.12

    Parameters

    • n: number

      The number to sum up to.

    Returns number

    The sum of all the numbers between 1 and n.

  • toDecimalMark(num: number): string
  • Converts a number to a decimal mark formatted string.

    example
    toDecimalMark(12305030388.9087); // '12,305,030,388.909'
    
    since

    0.1.15

    Parameters

    • num: number

      number to convert

    Returns string

    decimal mark formatted string

  • toOptionalFixed(num: number, digits: number): string
  • Number to fixed-point notation without trailing zeros

    example
    toOptionalFixed(1, 2); // '1'
    toOptionalFixed(1.001, 2); // '1'
    toOptionalFixed(1.500, 2); // '1.5'
    since

    0.1.14

    Parameters

    • num: number

      number to convert

    • digits: number

      number of digits to show

    Returns string

    fixed-point notation

  • toSafeInteger(num: number): number
  • Converts a value to a safe integer.

    example
    toSafeInteger(3.2); // 3
    toSafeInteger(Number.MIN_VALUE); // 0
    toSafeInteger(Infinity); // 9007199254740991
    since

    0.1.1

    Parameters

    • num: number

      The value to convert.

    Returns number

    A safe integer if the value is a number, otherwise NaN.

  • validateNumber(n: any): boolean
  • Checks if the given value is a number.

    example
    validateNumber('10'); // true
    validateNumber('a'); // false
    since

    0.1.15

    Parameters

    • n: any

      The value to check.

    Returns boolean

    true if the value is a number, false otherwise.

Object Functions

  • checkProp(predicate: (value: any) => any, prop: string): (obj: any) => boolean
  • Creates a function that will invoke a predicate function for the specified property on a given object.

    example
    const lengthIs4 = checkProp(l => l === 4, 'length');
    lengthIs4([]); // false
    lengthIs4([1, 2, 3, 4]); // true
    lengthIs4(new Set([1, 2, 3, 4])); // false (Set uses Size, not length)

    const session = { user: {} };
    const validUserSession = checkProp(u => u.active && !u.disabled, 'user');

    validUserSession(session); // false

    session.user.active = true;
    validUserSession(session); // true

    const noLength = checkProp(l => l === undefined, 'length');
    noLength([]); // false
    noLength({}); // true
    noLength(new Set()); // true
    since

    0.1.3

    Parameters

    • predicate: (value: any) => any

      The predicate function that will be invoked.

        • (value: any): any
        • Parameters

          • value: any

          Returns any

    • prop: string

      The property to check.

    Returns (obj: any) => boolean

    A function that will invoke the predicate function for the specified property on a given object.

      • (obj: any): boolean
      • Parameters

        • obj: any

        Returns boolean

  • deepMerge(a: Record<string, any>, b: Record<string, any>, fn: (key: string, a: any, b: any) => Record<string, any>): {}
  • Deeply merges two objects, using a function to handle keys present in both.

    example
    deepMerge(
    { a: true, b: { c: [1, 2, 3] } },
    { a: false, b: { d: [1, 2, 3] } },
    (key, a, b) => (key === 'a' ? a && b : Object.assign({}, a, b))
    );
    // { a: false, b: { c: [ 1, 2, 3 ], d: [ 1, 2, 3 ] } }
    since

    0.1.13

    Parameters

    • a: Record<string, any>

      The first object.

    • b: Record<string, any>

      The second object.

    • fn: (key: string, a: any, b: any) => Record<string, any>

      The function to use to handle keys present in both objects.

        • (key: string, a: any, b: any): Record<string, any>
        • Parameters

          • key: string
          • a: any
          • b: any

          Returns Record<string, any>

    Returns {}

    The merged object.

    • equals(a: any, b: any): boolean
    • Performs a deep comparison between two values to determine if they are equivalent.

      example
      equals(
      { a: [2, { e: 3 }], b: [4], c: 'foo' },
      { a: [2, { e: 3 }], b: [4], c: 'foo' }
      ); // true
      equals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }); // true
      since

      0.1.0

      Parameters

      • a: any

        The first value to compare.

      • b: any

        The second value to compare.

      Returns boolean

      true if the values are equivalent, otherwise false.

    • get(from: Record<string, any>, ...selectors: string[]): Record<string, any>[]
    • Retrieves a set of properties indicated by the given selectors from an object.

      example
      const obj = {
      selector: { to: { val: 'val to select' } },
      target: [1, 2, { a: 'test' }],
      };
      get(obj, 'selector.to.val', 'target[0]', 'target[2].a');
      // ['val to select', 1, 'test']
      since

      0.1.13

      Parameters

      • from: Record<string, any>

        The object to retrieve the properties from.

      • Rest ...selectors: string[]

        The selectors to retrieve the properties from.

      Returns Record<string, any>[]

      The retrieved properties.

    • isDeepFrozen(obj: Record<string, any>): boolean
    • Checks if an object is deeply frozen.

      example
      const x = Object.freeze({ a: 1 });
      const y = Object.freeze({ b: { c: 2 } });
      isDeepFrozen(x); // true
      isDeepFrozen(y); // false
      since

      0.1.9

      Parameters

      • obj: Record<string, any>

        The object to check.

      Returns boolean

      Whether the object is deeply frozen.

    • isSameOrigin(origin: URL, destination: URL): boolean
    • Checks if two URLs are on the same origin.

      example
      const origin = new URL('https://blog.ifable.cn/tags');
      const destination = new URL('https://blog.ifable.cn/categories');
      isSameOrigin(origin, destination); // true
      const other = new URL('https://developer.mozilla.org);
      isSameOrigin(origin, other); // false
      since

      0.1.3

      Parameters

      • origin: URL

        The origin to compare to.

      • destination: URL

        The destination to compare to.

      Returns boolean

      true if the origins are the same, false otherwise.

    • matches(obj: Record<string, any>, source: Record<string, any>): boolean
    • Compares two objects to determine if the first one contains equivalent property values to the second one.

      example
      matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true });
      // true
      matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true });
      // false
      since

      0.1.4

      Parameters

      • obj: Record<string, any>

        The object to compare.

      • source: Record<string, any>

        The source object to compare against.

      Returns boolean

      true if the objects are equivalent, otherwise false.

    • objectToPairs(obj: Record<string, any>): [string, any][]
    • Creates an array of key-value pair arrays from an object.

      example
      objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
      
      since

      0.1.3

      Parameters

      • obj: Record<string, any>

        The object to convert to pairs.

      Returns [string, any][]

      An array of key-value pair arrays.

    • queryStringToObject(url: string): {}
    • Generates an object from the given query string or URL.

      example
      queryStringToObject('https://google.com?page=1&count=10');
      // {page: '1', count: '10'}
      since

      0.1.16

      Parameters

      • url: string

        The URL to parse.

      Returns {}

      The object.

      • [key: string]: string
    • shallowClone(obj: Record<any, any>): {}
    • Creates a shallow clone of an object.

      example
      const a = { x: true, y: 1 };
      const b = shallowClone(a); // a !== b
      since

      0.1.3

      Parameters

      • obj: Record<any, any>

        The object to clone.

      Returns {}

      A shallow clone of the object.

      • size(val: any): any
      • Gets the size of an array, object or string.

        example
        size([1, 2, 3, 4, 5]); // 5
        size('size'); // 4
        size({ one: 1, two: 2, three: 3 }); // 3
        since

        0.1.10

        Parameters

        • val: any

          The value to get the size of.

        Returns any

        The size of the value.

      String Functions

      • CSVToArray(data: string, delimiter?: string, omitFirstRow?: boolean): string[][]
      • Converts a comma-separated values (CSV) string to a 2D array.

        throws

        If the CSV string is invalid.

        example
        CSVToArray('a,b\nc,d'); // [['a', 'b'], ['c', 'd']];
        CSVToArray('a;b\nc;d', ';'); // [['a', 'b'], ['c', 'd']];
        CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a', 'b'], ['c', 'd']];
        since

        0.1.10

        Parameters

        • data: string

          The CSV string.

        • delimiter: string = ","

          The delimiter used in the CSV string.

        • omitFirstRow: boolean = false

          Whether to omit the first row of the CSV string.

        Returns string[][]

        The 2D array.

      • CSVToJSON(data: string, delimiter?: string): {}[]
      • Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

        example
        CSVToJSON('col1,col2\na,b\nc,d');
        // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
        CSVToJSON('col1;col2\na;b\nc;d', ';');
        // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
        since

        0.1.15

        Parameters

        • data: string

          The CSV string.

        • delimiter: string = ","

          The delimiter used in the CSV string.

        Returns {}[]

        A 2D array of objects.

      • RGBToHex(r: number, g: number, b: number): string
      • Converts the values of RGB components to a hexadecimal color code.

        example
        RGBToHex(255, 165, 1); // 'ffa501'
        
        since

        0.1.10

        Parameters

        • r: number

          The red component.

        • g: number

          The green component.

        • b: number

          The blue component.

        Returns string

        The hexadecimal color code.

      • URLJoin(...args: string[]): string
      • Joins all given URL segments together, then normalizes the resulting URL.

        example
        URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
        // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
        since

        0.1.10

        Parameters

        • Rest ...args: string[]

          The URL segments to join.

        Returns string

        The joined URL.

      • capitalize(__namedParameters: string, lowerRest?: boolean): string
      • Capitalizes the first letter of a string.

        example
        capitalize('fooBar'); // 'FooBar'
        capitalize('fooBar', true); // 'Foobar'
        since

        0.1.10

        Parameters

        • __namedParameters: string
        • lowerRest: boolean = false

          Whether to lowercase the rest of the string.

        Returns string

        The capitalized string.

      • capitalizeEveryWord(str: string): string
      • Capitalizes the first letter of every word in a string.

        example
        capitalizeEveryWord('hello world') // 'Hello World'
        
        since

        0.1.3

        Parameters

        • str: string

          The string to capitalize.

        Returns string

        The capitalized string.

      • changeLightness(delta: number, hslStr: string): null | string
      • Changes the lightness value of an hsl() color string.

        example
        changeLightness(10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 60%)'
        changeLightness(-10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 40%)'
        since

        0.1.7

        Parameters

        • delta: number

          The amount to change the lightness by.

        • hslStr: string

          The hsl() color string to change.

        Returns null | string

        The changed hsl() color string.

      • Adds special characters to text to print in color in the console (combined with console.log()).

        example
        console.log(colorize('foo').red); // 'foo' (red letters)
        console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
        console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite);
        // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
        since

        0.1.0

        Parameters

        • Rest ...args: string[]

          The text to colorize.

        Returns ColorizeRecord

        The colorized text.

      • compactWhitespace(str: string): string
      • Compacts whitespaces in a string.

        example
        compactWhitespace('  a  b  ') // 'a b'
        
        since

        0.1.3

        Parameters

        • str: string

          The string to compact.

        Returns string

        The compacted string.

      • containsWhitespace(str: string): boolean
      • Checks if the given string contains any whitespace characters.

        example
        containsWhitespace('lorem'); // false
        containsWhitespace('lorem ipsum'); // true
        since

        0.1.1

        Parameters

        • str: string

          The string to check.

        Returns boolean

        true if the string contains any whitespace characters, otherwise false.

      • countSubstrings(str: string, searchValue: string): number
      • Counts the occurrences of a substring in a given string.

        example
        countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3
        countSubstrings('tutut tut tut', 'tut'); // 4
        since

        0.1.16

        Parameters

        • str: string

          The string to search.

        • searchValue: string

          The substring to search for.

        Returns number

        The number of occurrences of the substring in the string.

      • escapeHTML(str: string): string
      • Escapes a string for use in HTML.

        example
        escapeHTML('<a href="#">Me & you</a>');
        // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
        since

        0.1.6

        Parameters

        • str: string

          The string to escape.

        Returns string

        The escaped string.

      • escapeRegExp(str: string): string
      • Escapes a string to use in a regular expression.

        example
        escapeRegExp('(test)'); // \\(test\\)
        
        since

        0.1.1

        Parameters

        • str: string

          The string to escape.

        Returns string

        The escaped string.

      • expandTabs(str: string, count: number): string
      • Convert tabs to spaces, where each tab corresponds to count spaces.

        example
        expandTabs('\t\tlorem', 3); // '      lorem'
        
        since

        0.1.1

        Parameters

        • str: string

          The string to convert.

        • count: number

          The number of spaces to expand each tab to.

        Returns string

        The converted string.

      • extendHex(shortHex: string): string
      • Extends a 3-digit color code to a 6-digit color code.

        example
        extendHex('#f0') // '#ff00f0'
        extendHex('05a'); // '#0055aa'
        since

        0.1.16

        Parameters

        • shortHex: string

          The 3-digit color code.

        Returns string

        The 6-digit color code.

      • formatNumber(num: number): string
      • Formats a number using the local number format order.

        example
        formatNumber(123456); // '123,456' in `en-US`
        formatNumber(15675436903); // '15.675.436.903' in `de-DE`
        since

        0.1.1

        Parameters

        • num: number

          The number to format.

        Returns string

        The formatted number.

      • fromCamelCase(str: string, separator?: string): string
      • Converts a string from camelcase.

        example
        fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
        fromCamelCase('someLabelThatNeedsToBeDecamelized', '-');
        // 'some-label-that-needs-to-be-decamelized'
        fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
        fromCamelCase('JSONToCSV', '.'); // 'json.to.csv'
        since

        0.1.1

        Parameters

        • str: string

          The string to convert.

        • separator: string = "_"

          The separator to use.

        Returns string

        The converted string.

      • getBaseURL(url: string): string
      • Gets the current URL without any parameters or fragment identifiers.

        example
        getBaseURL('http://url.com/page?name=Adam&surname=Smith');
        // 'http://url.com/page'
        since

        0.1.5

        Parameters

        • url: string

          The URL to parse.

        Returns string

        The current URL without any parameters or fragment identifiers.

      • getURLParameters(url: string): {}
      • Creates an object containing the parameters of the current URL.

        example
        getURLParameters('google.com'); // {}
        getURLParameters('http://url.com/page?name=Adam&surname=Smith');
        // {name: 'Adam', surname: 'Smith'}
        since

        0.1.15

        Parameters

        • url: string

          The URL to parse.

        Returns {}

        An object containing the parameters of the current URL.

        • [key: string]: string
      • indentString(str: string, count: number, indent?: string): string
      • Indents each line in the provided string.

        example
        indentString('Lorem\nIpsum', 2); // '  Lorem\n  Ipsum'
        indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'
        since

        0.1.1

        Parameters

        • str: string

          The string to indent.

        • count: number

          The number of spaces to indent each line.

        • indent: string = " "

          The indentation character.

        Returns string

        The indented string.

      • indexOfSubstrings(str: string, searchValue: string): Generator<number, void, unknown>
      • Finds all the indexes of a substring in a given string.

        example
        [...indexOfSubstrings('tiktok tok tok tik tok tik', 'tik')]; // [0, 15, 23]
        [...indexOfSubstrings('tutut tut tut', 'tut')]; // [0, 2, 6, 10]
        [...indexOfSubstrings('hello', 'hi')]; // []
        since

        0.1.16

        Parameters

        • str: string

          The string to search in.

        • searchValue: string

          The substring to search for.

        Returns Generator<number, void, unknown>

        An array of indexes of the substring in the string.

      • isAbsoluteURL(str: string): boolean
      • Checks if the given string is an absolute URL.

        example
        isAbsoluteURL('https://google.com'); // true
        isAbsoluteURL('ftp://www.myserver.net'); // true
        isAbsoluteURL('/foo/bar'); // false
        since

        0.1.1

        Parameters

        • str: string

          The string to check.

        Returns boolean

        true if the string is an absolute URL, false otherwise.

      • isAlpha(str: string): boolean
      • Checks if a string contains only alpha characters.

        example
        sAlpha('sampleInput'); // true
        isAlpha('this Will fail'); // false
        isAlpha('123'); // false
        since

        0.1.1

        Parameters

        • str: string

          String to check

        Returns boolean

        True if str is alphanumeric, false otherwise

      • isAlphaNumeric(str: string): boolean
      • Checks if a string contains only alphanumeric characters.

        example
        isAlphaNumeric('hello123'); // true
        isAlphaNumeric('123'); // true
        isAlphaNumeric('hello 123'); // false (space character is not alphanumeric)
        isAlphaNumeric('#$hello'); // false
        since

        0.1.1

        Parameters

        • str: string

          The string to check.

        Returns boolean

        True if the string contains only alphanumeric characters, false otherwise.

      • isLowerCase(string: string): boolean
      • Checks if a string is lower case.

        example
        isLowerCase('abc'); // true
        isLowerCase('a3@$'); // true
        isLowerCase('Ab4'); // false
        since

        0.1.0

        Parameters

        • string: string

          String to check.

        Returns boolean

        Returns true if the string is lower case, false otherwise.

      • isUpperCase(string: string): boolean
      • Checks if a string is upper case.

        example
        isUpperCase('ABC'); // true
        isUpperCase('A3@$'); // true
        isUpperCase('aB4'); // false
        since

        0.1.0

        Parameters

        • string: string

          String to check.

        Returns boolean

        Returns true if the string is upper case, false otherwise.

      • mapString(str: string, fn: (c: string, i: number, str: string) => string): string
      • Creates a new string with the results of calling a provided function on every character in the given string.

        example
        mapString('abc', (c) => c.toUpperCase()); // 'ABC'
        
        since

        0.1.16

        Parameters

        • str: string

          The string to map.

        • fn: (c: string, i: number, str: string) => string

          The function to call for each character.

            • (c: string, i: number, str: string): string
            • Parameters

              • c: string
              • i: number
              • str: string

              Returns string

        Returns string

        The new string.

      • mask(cc: number, num?: number, mask?: string): string
      • 用指定的掩码字符替换除最后 num 个字符之外的所有字符

        example
        mask('123456789', '*', 3) // '******789'
        
        since

        0.1.0

        Parameters

        • cc: number

          待替换的数字

        • Optional num: number

          最后保留的字符数

        • Optional mask: string

          掩码字符

        Returns string

        替换后的字符串

      • normalizeLineEndings(str: string, normalized?: string): string
      • Normalizes line endings in a string.

        example
        normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n');
        // 'This\r\nis a\r\nmultiline\r\nstring.\r\n'
        normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n', '\n');
        // 'This\nis a\nmultiline\nstring.\n'
        since

        0.1.1

        Parameters

        • str: string

          The string to normalize.

        • normalized: string = "\r\n"

          The normalized string.

        Returns string

        The normalized string.

      • pad(str: string, length: number, char?: string): string
      • Pads a string on both sides with the specified character, if it's shorter than the specified length.

        example
        pad('cat', 8); // '  cat   '
        pad(String(42), 6, '0'); // '004200'
        pad('foobar', 3); // 'foobar'
        since

        0.1.1

        Parameters

        • str: string

          The string to pad.

        • length: number

          The length of the resulting string.

        • char: string = " "

          The character to pad with.

        Returns string

        The padded string.

      • padNumber(n: number, l: number): string
      • 用零向左填充指定长度的数字

        example
        padNumber(1, 3) // returns '001'
        padNumber(1234, 6) // '001234'
        since

        0.1.0

        Parameters

        • n: number

          number to pad

        • l: number

          length of the resulting string

        Returns string

        padded number

      • parseCookie(str: string): Record<string, string>
      • Parses an HTTP Cookie header string, returning an object of all cookie name-value pairs.

        example
        parseCookie('foo=bar; equation=E%3Dmc%5E2');
        // { foo: 'bar', equation: 'E=mc^2' }
        since

        0.1.7

        Parameters

        • str: string

          The cookie header string to parse.

        Returns Record<string, string>

        An object of cookie name-value pairs.

      • randomAlphaNumeric(length: number): string
      • Generates a random string with the specified length.

        example
        randomAlphaNumeric(5); // '0afad'
        
        since

        0.1.10

        Parameters

        • length: number

          The length of the string to generate.

        Returns string

        The random string.

      • removeAccents(str: string): string
      • Removes accents from strings.

        example
        removeAccents('Antoine de Saint-Exupéry'); // 'Antoine de Saint-Exupery'
        
        since

        0.1.10

        Parameters

        • str: string

          The string to remove accents from.

        Returns string

        The string without accents.

      • removeNonASCII(str: string): string
      • Removes non-printable ASCII characters.

        example
        removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'
        
        since

        0.1.3

        Parameters

        • str: string

          String to remove non-printable ASCII characters from.

        Returns string

        String with non-printable ASCII characters removed.

      • removeWhitespace(str: string): string
      • Returns a string with whitespaces removed.

        example
        removeWhitespace('  foo  '); // 'foo'
        removeWhitespace('Lorem ipsum.\n Dolor sit amet. ');
        // 'Loremipsum.Dolorsitamet.'
        since

        0.1.3

        Parameters

        • str: string

          The string to remove whitespaces from.

        Returns string

        The string with whitespaces removed.

      • replaceLast(str: string, pattern: string | RegExp, replacement: string): string
      • Replaces the last occurence of a pattern in a string.

        example
        replaceLast('abcabdef', 'ab', 'gg'); // 'abcggdef'
        replaceLast('abcabdef', /ab/, 'gg'); // 'abcggdef'
        replaceLast('abcabdef', 'ad', 'gg'); // 'abcabdef'
        replaceLast('abcabdef', /ad/, 'gg'); // 'abcabdef'
        since

        0.1.16

        Parameters

        • str: string

          The string to search.

        • pattern: string | RegExp

          The pattern to search for.

        • replacement: string

          The string to replace the pattern with.

        Returns string

        The resulting string.

      • serializeCookie(name: string | number, val: string | number | boolean): string
      • Serializes a cookie name-value pair into a Set-Cookie header string.

        example
        serializeCookie('foo', 'bar'); // "foo=bar"
        
        since

        0.1.1

        Parameters

        • name: string | number

          The cookie name.

        • val: string | number | boolean

          The cookie value.

        Returns string

        The Set-Cookie header string.

      • slugify(str: string): string
      • Converts a string to a URL-friendly slug.

        example
        slugify('Hello World!'); // 'hello-world'
        
        since

        0.1.3

        Parameters

        • str: string

          The string to convert.

        Returns string

        The slugified string.

      • splitLines(str: string): string[]
      • Splits a multiline string into an array of lines.

        example
        splitLines('This\nis a\nmultiline\nstring.\n');
        // ['This', 'is a', 'multiline', 'string.' , '']
        since

        0.1.10

        Parameters

        • str: string

          The string to split.

        Returns string[]

        The array of lines.

      • stripHTMLTags(str: string): string
      • Removes HTML/XML tags from string.

        example
        stripHTMLTags('<p>Hello</p>'); // 'Hello'
        
        since

        0.1.1

        Parameters

        • str: string

          string to remove tags from

        Returns string

        string without tags

      • swapCase(str: string): string
      • Creates a string with uppercase characters converted to lowercase and vice versa.

        example
        swapCase('Hello World') // 'hELLO wORLD'
        
        since

        0.1.16

        Parameters

        • str: string

          The string to convert.

        Returns string

        The converted string.

      • toCamelCase(str: string): string
      • Converts a string to camelcase.

        example
        toCamelCase('Foo Bar'); // 'fooBar'
        toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
        toCamelCase('Some label that needs to be camelized');
        // 'someLabelThatNeedsToBeCamelized'
        toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
        toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
        // 'someMixedStringWithSpacesUnderscoresAndHyphens'
        since

        0.1.16

        Parameters

        • str: string

          String to convert.

        Returns string

        Camelcased string.

      • toCharArray(s: string): string[]
      • Converts a string to an array of characters.

        example
        toCharArray("Hello") // ["H", "e", "l", "l", "o"]
        
        since

        0.1.4

        Parameters

        • s: string

          The string to convert.

        Returns string[]

        An array of characters.

      • toHSLArray(hslStr: string): undefined | number[]
      • Converts an hsl() color string to an array of values.

        example
        toHSLArray('hsl(50, 10%, 10%)'); // [50, 10, 10]
        
        since

        0.1.6

        Parameters

        • hslStr: string

          The hsl() color string to convert.

        Returns undefined | number[]

        The HSL values.

      • toHSLObject(hslStr: string): null | { hue: number; lightness: number; saturation: number }
      • Converts an hsl() color string to an object with the values of each color.

        example
        toHSLObject('hsl(0, 100%, 50%)');
        // { hue: 0, saturation: 100, lightness: 50 }
        since

        0.1.7

        Parameters

        • hslStr: string

          The hsl() color string to convert.

        Returns null | { hue: number; lightness: number; saturation: number }

        An object with the values of each color.

      • toPascalCase(str: string): undefined | string
      • Converts a string to pascal case.

        example
        toPascalCase("foo-bar") // "FooBar"
        toPascalCase('some_database_field_name'); // 'SomeDatabaseFieldName'
        toPascalCase('Some label that needs to be pascalized');
        // 'SomeLabelThatNeedsToBePascalized'
        toPascalCase('some-javascript-property'); // 'SomeJavascriptProperty'
        toPascalCase('some-mixed_string with spaces_underscores-and-hyphens');
        // 'SomeMixedStringWithSpacesUnderscoresAndHyphens'
        since

        0.1.16

        Parameters

        • str: string

          The string to convert.

        Returns undefined | string

        The string in pascal case.

      • toRGBArray(rgbStr: string): undefined | number[]
      • Converts an rgb() color string to an array of values.

        example
        toRGBArray('rgb(255, 12, 0)'); // [255, 12, 0]
        
        since

        0.1.6

        Parameters

        • rgbStr: string

          The rgb() color string to convert.

        Returns undefined | number[]

        The RGB values.

      • toRGBObject(rgbStr: string): null | { blue: number; green: number; red: number }
      • Converts an rgb() color string to an object with the values of each color.

        example
        toRGBObject('rgb(255, 0, 0)'); // { red: 255, green: 0, blue: 0 }
        
        since

        0.1.7

        Parameters

        • rgbStr: string

          The rgb() color string to convert.

        Returns null | { blue: number; green: number; red: number }

        An object with the values of each color.

      • toSnakeCase(str: string): undefined | string
      • Converts a string to snake case.

        example
        toSnakeCase('FooBar') // 'foo_bar'
        toSnakeCase('camelCase'); // 'camel_case'
        toSnakeCase('some text'); // 'some_text'
        toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens');
        // 'some_mixed_string_with_spaces_underscores_and_hyphens'
        toSnakeCase('AllThe-small Things'); // 'all_the_small_things'
        toSnakeCase('IAmEditingSomeXMLAndHTML');
        // 'i_am_editing_some_xml_and_html'
        since

        0.1.16

        Parameters

        • str: string

          The string to convert.

        Returns undefined | string

        The snake cased string.

      • toTitleCase(str: string): undefined | string
      • Converts a string to title case.

        example
        toTitleCase('some_database_field_name'); // 'Some Database Field Name'
        toTitleCase('Some label that needs to be title-cased');
        // 'Some Label That Needs To Be Title Cased'
        toTitleCase('some-package-name'); // 'Some Package Name'
        toTitleCase('some-mixed_string with spaces_underscores-and-hyphens');
        // 'Some Mixed String With Spaces Underscores And Hyphens'
        since

        0.1.16

        Parameters

        • str: string

          The string to convert.

        Returns undefined | string

        The converted string.

      • truncateString(string: string, num: number): string
      • Truncates a string up to a specified length.

        example
        truncateString("Hello World", 5); // "Hello..."
        

        Parameters

        • string: string

          The string to truncate.

        • num: number

          The maximum length of the string.

        Returns string

        The truncated string.

      • truncateStringAtWhitespace(str: string, lim: number, ending?: string): string
      • Truncates a string up to specified length, respecting whitespace when possible.

        example
        truncateStringAtWhitespace('short', 10); // 'short'
        truncateStringAtWhitespace('not so short', 10); // 'not so...'
        truncateStringAtWhitespace('trying a thing', 10); // 'trying...'
        truncateStringAtWhitespace('javascripting', 10); // 'javascr...'
        since

        0.1.1

        Parameters

        • str: string

          The string to truncate.

        • lim: number

          The maximum length of the string.

        • ending: string = "..."

          The string to append to the end of the truncated string.

        Returns string

        The truncated string.

      • unescapeHTML(str: string): string
      • Unescapes escaped HTML characters.

        example
        unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;');
        // '<a href="#">Me & you</a>'
        since

        0.1.6

        Parameters

        • str: string

          The string to unescape.

        Returns string

        The unescaped string.

      • wordWrap(str: string, max: number, br?: string): string
      • Wraps a string to a given number of characters using a string break character.

        example
        wordWrap(
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.',
        32
        );
        // 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit.\nFusce tempus.'
        wordWrap(
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.',
        32,
        '\r\n'
        );
        // 'Lorem ipsum dolor sit amet,\r\nconsectetur adipiscing elit.\r\nFusce tempus.'
        since

        0.1.3

        Parameters

        • str: string

          The string to wrap.

        • max: number

          The maximum number of characters per line.

        • br: string = "\n"

          The string break character.

        Returns string

        The wrapped string.

      Type Functions

      • castArray(value: any): any[]
      • Casts the provided value as an array if it's not one.

        example
        castArray('foo'); // ['foo']
        castArray([1]); // [1]
        castArray(null); // [null]
        castArray(undefined); // [undefined]
        since

        0.1.0

        Parameters

        • value: any

          The value to cast as an array.

        Returns any[]

        The value as an array.

      • cloneRegExp(regExp: RegExp): RegExp
      • Clones a regular expression.

        example
        const regExp = /lorem ipsum/gi;
        const regExp2 = cloneRegExp(regExp); // regExp !== regExp2
        since

        0.1.0

        Parameters

        • regExp: RegExp

          The regular expression to clone.

        Returns RegExp

        The cloned regular expression.

      • coalesce(...args: any[]): any
      • Returns the first defined, non-null argument.

        throws

        If no arguments are defined.

        example
        coalesce(null, undefined, '', NaN, 'Waldo'); // ''
        
        since

        0.1.0

        Parameters

        • Rest ...args: any[]

          The arguments to check.

        Returns any

        The first defined, non-null argument.

      • getType(value: any): string
      • Returns the native type of a value.

        example
        getType(1) // Number
        getType(true) // Boolean
        getType(null) // null
        getType(undefined) // undefined
        getType(Symbol()) // Symbol
        getType(new Map()) // Map
        getType(new Set()) // Set
        since

        0.1.0

        Parameters

        • value: any

          The value to get the type of.

        Returns string

        The native type of the value.

      • is<T>(type: new (...args: any[]) => T, val: any): boolean
      • Checks if the provided value is of the specified type.

        example
        is<Array<number>>(Array, [1]); // true
        is<ArrayBuffer>(ArrayBuffer, new ArrayBuffer(10)); // true
        is<Map>(Map, new Map()); // true
        is<RegExp>(RegExp, /./g); // true
        is<Set>(Set, new Set()); // true
        is<WeakMap>(WeakMap, new WeakMap()); // true
        is<WeakSet>(WeakSet, new WeakSet()); // true
        is<String>(String, ''); // true
        is<String>(String, new String('')); // true
        is<Number>(Number, 1); // true
        is<Number>(Number, new Number(1)); // true
        is<Boolean>(Boolean, true); // true
        is<Boolean>(Boolean, new Boolean(true)); // true
        is<Object>(Object, {}); // true
        is<Object>(Object, new Object()); // true
        is<Function>(Function, () => {}); // true
        is<Function>(Function, new Function()); // true
        since

        0.1.0

        Type parameters

        • T

        Parameters

        • type: new (...args: any[]) => T

          The type to check against.

            • new (...args: any[]): T
            • Parameters

              • Rest ...args: any[]

              Returns T

        • val: any

          The value to check.

        Returns boolean

        True if the value is of the specified type, false otherwise.

      • isArrayLike(obj: any): boolean
      • Checks if the provided argument is array-like (i.e. is iterable).

        example
        isArrayLike([1, 2, 3]); // true
        isArrayLike(document.querySelectorAll('.className')); // true
        isArrayLike('abc'); // true
        isArrayLike(null); // false
        since

        0.1.0

        Parameters

        • obj: any

          The object to check.

        Returns boolean

        True if the object is array-like, false otherwise.

      • isAsyncFunction(value: any): boolean
      • Checks if the given argument is an async function.

        example
        isAsyncFunction(function() {}); // false
        isAsyncFunction(async function() {}); // true
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        true if the given argument is an async function; otherwise, false.

      • isBoolean(value: any): boolean
      • Checks if the given argument is a native boolean element.

        example
        isBoolean(null); // false
        isBoolean(false); // true
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        If the given argument is a native boolean element.

      • isEmpty(value: any): boolean
      • Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.

        example
        isEmpty([]); // true
        isEmpty({}); // true
        isEmpty(''); // true
        isEmpty([1, 2]); // false
        isEmpty({ a: 1, b: 2 }); // false
        isEmpty('text'); // false
        isEmpty(123); // true - type is not considered a collection
        isEmpty(true); // true - type is not considered a collection
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        True if the value is an empty object/collection, false otherwise.

      • isFunction(value: any): boolean
      • Checks if the given argument is a function.

        example
        isFunction('x') // false
        isFunction(x => x) // true
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        Returns true if the value is an object, false otherwise.

      • isGeneratorFunction(value: any): boolean
      • Checks if the given argument is a generator function.

        example
        isGeneratorFunction(function() {}); // false
        isGeneratorFunction(function*() {}); // true
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        true if the given argument is a generator function; otherwise, false.

      • isNil(value: any): boolean
      • 检查指定的值是否为 null 或 undefined

        example
        isNil(null); // => true
        isNil(undefined); // => true
        isNil(0); // => false
        since

        0.1.0

        Parameters

        • value: any

          要检查的值

        Returns boolean

        如果值为null或undefined,则返回true,否则返回false

      • isNull(value: any): boolean
      • 检查指定的值是否为null

        example
        isNull(null) // true
        isNull(undefined) // false
        since

        0.1.0

        Parameters

        • value: any

          要检查的值

        Returns boolean

        如果值为null,则返回true

      • isNumber(value: any): boolean
      • Checks if the given argument is a number.

        example
        isNumber(1); // true
        isNumber('1'); // false
        isNumber(NaN); // false
        isNumber(Infinity); // false
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        True if the given argument is a number, false otherwise.

      • isObject(value: any): boolean
      • Checks if the passed value is an object or not.

        example
        isObject([1, 2, 3, 4]); // true
        isObject([]); // true
        isObject(['Hello!']); // true
        isObject({ a: 1 }); // true
        isObject({}); // true
        isObject(true); // false
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        Returns true when the passed value is an object, false otherwise.

      • isObjectLike(value: any): boolean
      • Checks if a value is object-like.

        example
        isObjectLike({}); // true
        isObjectLike([1, 2, 3]); // true
        isObjectLike(x => x); // false
        isObjectLike(null); // false
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        Returns true if value is object-like, else false.

      • isPlainObject(value: any): boolean
      • Checks if the provided value is an object created by the Object constructor.

        example
        isPlainObject({ a: 1 }); // true
        isPlainObject(new Map()); // false
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        Returns true if value is an object created by the Object constructor, else false.

      • isPrimitive(value: any): boolean
      • Checks if the passed value is primitive or not.

        example
        isPrimitive(null); // => true
        isPrimitive(undefined); // => true
        isPrimitive(true); // => true
        isPrimitive(1); // => true
        isPrimitive([]); // => false
        isPrimitive({}); // => false
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        true if the value is primitive, false otherwise.

      • isPromiseLike(value: any): boolean
      • Checks if an object looks like a Promise.

        example
        isPromiseLike({ then: () => {} }) // true
        isPromiseLike(Promise.resolve()) // true
        isPromiseLike(new Promise(() => {})) // true
        isPromiseLike(null) // false
        since

        0.1.0

        Parameters

        • value: any

          The object to check.

        Returns boolean

        If value looks like a Promise.

      • isString(value: any): boolean
      • Checks if the given argument is a string. Only works for string primitives.

        example
        isString('10'); // true
        
        since

        0.1.0

        Parameters

        • value: any

          The value to check.

        Returns boolean

        True if the value is a string, false otherwise.

      • isSymbol(value: any): boolean
      • 检查给定的参数是否是symbol

        example
        isSymbol(Symbol('x')) // => true
        isSymbol(1) // => false
        since

        0.1.0

        Parameters

        • value: any

          要检查的值

        Returns boolean

        如果是symbol则返回true,否则返回false

      • isUndefined(value: any): boolean
      • 检查指定的值是否为undefined

        example
        isUndefined(undefined) // true
        isUndefined(null) // false
        since

        0.1.0

        Parameters

        • value: any

          要检查的值

        Returns boolean

        如果值为undefined,则返回true

      • isValidJSON(json: any): boolean
      • Checks if the provided string is a valid JSON.

        example
        isValidJSON('{"foo": "bar"}'); // true
        isValidJSON('{"foo": "bar"'); // false
        since

        0.1.0

        Parameters

        • json: any

          The value to check.

        Returns boolean

        true if the string is a valid JSON, false otherwise.