@jsfns/ core web

v. 1.2.1
npm Github

# camelCase

camelCase(input: string, settings?: CamelCaseSettings): string

Transform a string into a camelCased word (eg. 'camel case' -> 'camelCase')

@returns : The formatted string

Examples
camelCase('data-value2-input'); // --> dataValue2input
camelCase('XML data input'); // --> XmlDataInput

// With settings
const settings = { abbr: true, numbers: true, upper: true };

camelCase('data-VALUE2-input', settings); // --> DataVALUE2Input

# capitalize

capitalize(str: string): string

Capitalize each word in a phrase

@returns : Capitalized string

Examples
capitalize('capitalize this phrase'); // --> Capitalize This Phrase
capitalize('capitalize-This-phrase'); // --> Capitalize-This-Phrase

# chunkString

chunkString(str: string, options?: ChunkStringOptions): string[]

Split a String up into smaller strings of a give size (eg. 'ABCDEF' -> [AB,CD,EF])

@returns : Array of chunks

Examples
chunkString('abcdefghijkl'); // --> ['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
chunkString('abcdefghij', { size: 4 }); // --> ['abcd', 'efgh', 'ij']
chunkString('abcdefghij', { size: 4, reverse: true }); // --> ['ab', 'cdef', 'ghij']

# debounce

debounce(callback: T, ms?: number): DebouncedFunction<T>

Ensure that the givcen callback function will only be called ms milliseconds after the last call.
This ensures to not trigger too many consecutive calls, but only the last in the sequence.

@returns : The debounce enabled function

# formatCurrency

formatCurrency(thousandTemplate?: string): CurrencyFormatter

Creates a function that formats a number to a given currency format (eg. 1000 -> 1.000,00 €)

The template string should be the number 1000 described with before and after
symbols (no numbers), a thousand separator and a decimal separator followed by
the number of decimals defined with zeroes: [before]1[thou.]000[dec.]00[after] -> $ 1,000.00

@returns : Curried function to format a given number

Examples
// Format number to default currency format (euro)
const euro = formatCurrency();
euro(2345234.678); // --> '2.345.234,68 €'

// Format number to USD currency format
const usd = formatCurrency('$ 1,000.00');
usd(2345234.678); // --> '$ 2,345,234.68'

// Format number to custom currency format
const custom = formatCurrency('# 1-000;00 ¤');
custom(2345234.678); // --> '# 2-345-234;68 ¤'

// Specifying number of decimals
const sixDecimals = formatCurrency('$ 1,000.000000');
sixDecimals(2345234.678); // --> '$ 2,345,234.678000'
sixDecimals(234.12345678); // --> '$ 234.123457'

# formatNumber

formatNumber(num: number, settings?: FormatNumberSettings): string

Formats a number with defined thousand and decimal separator, and a decimal limit
(see limitDecimals for details on decimalCount)

@returns : Formatted number as a string

Examples
// Default format
formatNumber(123456); // --> 123.456,00

// Custom format
formatNumber(123456, { decimalCount: '>3', thousand: '-', decimal: ':' }); // --> 123-456:000

# fuzzySearch

fuzzySearch(input: string, searchWord: string, options?: FuzzySearchOptions): boolean

Match the given search word (collection of characters) could be found in in a given input (word or phrase)

@returns : if the searchWord was found in the input or not

Examples
fuzzySearch('search me', 'src') // => true
fuzzySearch('search me', 'ache') // => true
fuzzySearch('search me', 'reach') // => false

# hash

hash(str: string): string

Generates a unique hash (DJB2) string from a string

@returns : Hash string

Examples
hash('Hash this string'); // --> sg463l
hashCode(str: string): number

Generates a unique numeric hash (DJB2) code from a string

@returns : Hash code

Examples
hashCode('Hash this string'); // --> 1720121313

# hexToNumber

hexToNumber(hex: string): number

@returns : Numeric representation of the hex code

# hexToRGB

hexToRGB(hex: string): number[]

Converts a Hexadecimal color to a RGB(A) color array

@returns : Array with RGB values

Examples
hexToRGB('#fff'); // --> [255, 255, 255]
hexToRGB('#2fd466'); // --> [47, 212, 102]

// And with alpha channel
hexToRGB('#2fd46680'); // --> [47, 212, 102, 0.5]

# isBoolean

isBoolean(x: unknown): boolean (x is boolean)

@returns : Whether the argument a Boolean or not

# isFunction

isFunction(x: unknown): boolean (x is undefined)

Is the given argument a Function

@returns : Whether the argument a Function or not

Examples
isFunction(() => {}); // --> true
isFunction('string'); // --> false

# isGenerator

isGenerator(x: unknown): boolean (x is GeneratorFunction)

Determine if the given argument is a Generator Function

@returns : Whether the argument a Generator or not

Examples
function* gen() {}

isGenerator(gen); // --> true
isGenerator(() => {}); // --> false
isGeneratorLike(x: unknown): boolean (x is Generator)

Determine if the given argument is a Generator object.
(A generator is the one created when calling a generator function)

@returns : Whether the argument a Generator like function or not

Examples
function *gen() {}

isGeneratorLike(gen()); // --> true
isGeneratorLike({ next() {}, throw() {} return() {} [Symbol.iterator]() {} }); // --> true
isGeneratorLike(() => {}); // --> false

# isNumber

isNumber(x: unknown): boolean (x is number)

@returns : Whether the argument a finite number or not

# isNumeric

isNumeric(x: unknown): boolean

Is the given argument is a finite numeric value (number as string or number directly) or not.

@returns : Whether the given argument is a numeric value

Examples
isNumeric(123); // --> true
isNumeric('123'); // --> true
isNumeric(Infinity); // --> false

# isObject

isObject(x: unknown): boolean (x is object)

@returns : Whether the argument a plain object or not

# isString

isString(x: unknown): boolean (x is string)

@returns : Whether the argument is a string or not

# kebabCase

kebabCase(str: string, settings?: PhrasifySettings): string

Transform phrase into a dashed phrase
(eg. 'camelCase' -> 'camel-case' or 'spaced phrase' -> 'spaced-phrase')

@returns : The string with spaces replaced by a dash (-)

Examples
kebabCase('some dashed phrase'); // --> some-dashed-phrase
kebabCase('dash version1 beta', { numbers: true }); // --> dash-version-1-beta

# leadingZero

leadingZero(num: number | string, len?: number): string

@returns : The given number as a string padded with zeroes to match the given min length

# limitDecimals

limitDecimals(num: number, decimalCount?: string | number): string

Limit decimals of a floating number to specified length. The length depends on decimalCount
which can have the following settings (eg. 2 or ">3" or "<5"):

Char Description
>n Minimum number of decimals, if the current number of decimals are shorter than the defined length, extra 0 (zeros) will be added.
<n Maximum number of decimals, longer decimals will be rounded and shortened down to this number.
n Match this exact number of decimals, rounding longer decimals and adding extra 0 (zeroes) to shorter ones.

@returns : String representation of the number with the decimals adjusted according to the decimal setting

Examples
// Exact number of decimals
limitDecimals(123.4567) // --> 123.46
limitDecimals(123, 5) // --> 123.00000

// Max number of decimals
limitDecimals(123.4567, '<3') // --> 123.457
limitDecimals(123, '<3') // --> 123

// Min number decimals
limitDecimals(123.4, '>4') // --> 123.4000
limitDecimals(123.456789, '>4') // --> 123.456789

// Min, Max number decimals
limitDecimals(123.4, '2,4') // --> 123.40
limitDecimals(123.456789, '2,4') // --> 123.4568

# minMax

minMax(num: number, min: number, max: number): number

@returns : The number limited to the min/max boundaries

# numberToHex

numberToHex(num: number): string

@returns : Hex representation of the given number

# pascalCase

pascalCase(input: string, settings?: PascalCaseSettings): string

@returns : The formatted string

# phrasify

phrasify(input: string, settings?: PhrasifySettings): string

Transform a string into a space separated phrase

@returns : The transformed phrase or word

Examples
phrasify('XMLDataInput'); // --> XML data input
phrasify('dataVALUE2-input', { numbers: true }); // --> data VALUE 2 input

# popAtIndex

popAtIndex(list: T[], index: number): undefined | T

Removes and returns an entry from a given array, at a designated index position.

Note

This is not a pure function and will alter the given array internally

Examples
popIndex([1,2,3], 1); // --> 2 (array will then be [1, 3])
popAtIndexPure(list: unknown[], index: number): [unknown, unknown[]]

Removes and returns an entry from a given array, at a designated index position.

@returns : An array with two entries: the first entry is the value just removed and the second
is the new array with the entry removed.

Examples
popIndexPure([1,2,3], 1); // --> [2,  [1, 3]]

# promisefy

promisefy(fn: PromisefyCallback): PromisefiedFunction

Converts a callback based action into one returning a Promise instead.

@returns : The promisefied function

Examples
function action(name, callback) { ... callback(); }

action = promisefy(action);

action
  .then(() => 'all good')
  .catch(() => 'Something went wrong');

# randomCryptoId

randomCryptoId(length?: number): string

Generate a random id of designated length - using cryptographic secure random numbers,
so it is a bit slower than randomId

Note

This method differs from crypto.randomUUID() in the way that it can be of any specified length
and doesn't contain any "-".
The methods would be slightly slower than randomId since it is using crypto.getRandomValues(),
but it is a more secure method.

@returns : A random generated id of a specified length

Examples
randomCryptoId(); // --> eg. 'efuc6f1n4xf'
randomCryptoId(20); // --> eg. '3vsmrbxlh9at0vhcsf1xh'

# randomHexColor

randomHexColor(): string

@returns : A random hex color

# randomId

randomId(length?: number): string

Generate a random id of designated length

@returns : A random generated id of a specified length

Examples
randomId(); // --> eg. 'efuc6f1n4xf'
randomId(20); // --> eg. '3vsmrbxlh9at0vhcsf1xh'

# randomInt

randomInt(min: number, max: number): number

Returns a random integer from a base number or range of numbers

@returns : A random number between the given min and max

Examples
randomInt(100, 200); // --> a number between 100 and 200
randomInt(max?: number): number

Returns a random integer from a base number or range of numbers

@returns : A random number between 0 and the given max

Examples
// Any random number
randomInt(); // --> a number between 0 and Number.MAX_SAFE_INTEGER

// With max number
randomInt(100); // --> a number between 0 and 100

# randomRGBColor

randomRGBColor(): [r: number, g: number, b: number]

@returns : An Array with random R G B values

# RGBToHex

RGBToHex(rgb: RGBTuple): string

Converts an Array of R G B (A) colors into a hex color.

@returns : A Hex representation of the given color

Examples
RGBToHex([123, 123, 123]) // --> #7b7b7b

// With alpha channel
RGBToHex([123, 123, 123, 0.5]) // --> #7b7b7b80
RGBToHex(r: number, g: number, b: number, a?: number): string

Converts R G B (A) color arguments into a hex color.

@returns : A Hex representation of the given colors

Examples
// RGB as arguments
RGBToHex( 123, 123, 123 ) // --> #7b7b7b80

// With alpha channel
RGBToHex( 123, 123, 123, 0.5 ) // --> #7b7b7b80

# safeDateChange

safeDateChange(from: Date, to: Date): Date

Verifies and corrects Dates where the month could accidentally have skipped into the
next month because the date is out of bounds by the month changed to.

@returns : Altered "to" date

Examples
const date = new Date(2017, 0, 31);
newDate = new Date(date);
newDate.setMonth(1);

// Normally you would expect "newDate" month to be February, but since the date
// of the previous date was 31 and february max date is 28 (or 29), the actual
// "newDate" is "Match 3rd 2017" (or 2nd). Using this function keeps it at "February 28 2017"

safeDateChange(date, newDate);

// newDate === "February 28 2017"

# snakeCase

snakeCase(str: string, settings?: PhrasifySettings): string

Transform phrase into a snake_case phrase
(eg. 'camelCase' -> 'camel-case' or 'spaced phrase' -> 'spaced-phrase')

@returns : The string transformed to snake_case

Examples
snakeCase('Convert This phrase'); // --> convert_this_phrase
snakeCase('dash VERSION1 beta', { numbers: true }); // --> dash_version_1_beta

# throttle

throttle(callback: T, ms?: number): T

Ensure that the given callback function can only be called every ms milliseconds

@returns : The throttled function

# truncate

truncate(str: string, settings?: TruncateSettings): string

Limits a string to a given number of characters and adds '...' in the end

@returns : The truncated string

Examples
truncate('No max length to the string'); // --> No max limit to the string length
truncate('With a max length to the string', { maxLength: 10 }); // --> With a max...
truncate('With a max length to the string and a different ending', { maxLength: 10, end: ' <---' }); // --> With a max <---

# uniqueArray

uniqueArray(arr: ArrayLike<T> | Iterable<T, any, any>): T[]

Filter out duplicate values from an array

@returns : A list with only unique items

Examples
uniqueArray([1,2,3,1,4,5,3,7]); // --> [1,2,3,4,5,6,7]
uniqueArray(document.querySelectorAll('.my-elm, .selected')); // --> unique array of elements (so .my-elm.selected will only be present once)
type CamelCaseSettings = PhrasifySettings & {
  // Keep abbreviations uppercase (false == HTMLElement => HtmlElement | true == HTMLElement => HTMLElement)
  abbr?: boolean
  // Convert to UpperCase CamelCase (aka PascalCase)
  upper?: boolean
};
type ChunkStringOptions = {
  reverse?: boolean
  size?: number
};
type DebouncedFunction = T & {
  cancelDebounce: () => void
};
type CurrencyFormatter = (num: number) => string;
type FormatNumberSettings = {
  // The decimal separator character
  decimal?: string
  // How many decimals to show
  decimalCount?: number | string
  // The thousand separator character
  thousand?: string
};
type FuzzySearchOptions = {
  caseSensitive: boolean
};
type KebabCaseSettings = PhrasifySettings;
type PascalCaseSettings = Omit<CamelCaseSettings, 'upper'>;
type PhrasifySettings = {
  // Separate numbers from words?
  numbers?: boolean
};
type NodeLikeCallback = (err?: string | Error | null, data?: unknown) => unknown;
type PromisefiedFunction = (args: any[]) => Promise<any>;
type PromisefyCallback = (args: any[]) => any;
type RGBTuple = [red: number, green: number, blue: number, alpha?: number];
type SnakeCaseSettings = PhrasifySettings;
type TruncateSettings = {
  // What ending to give the truncated string (default is "...")
  end?: string
  // Max length of the given string
  maxLength?: number
};