# 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
Types
type CamelCaseSettings = PhrasifySettings & {
// Keep abbreviations uppercase (false == HTMLElement => HtmlElement | true == HTMLElement => HTMLElement)
abbr?: boolean
// Convert to UpperCase CamelCase (aka PascalCase)
upper?: boolean
};
# 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']
Types
type ChunkStringOptions = {
reverse?: boolean
size?: number
};
# 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'
Types
type CurrencyFormatter = (num: number) => string;
# 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
Types
type FormatNumberSettings = {
// The decimal separator character
decimal?: string
// How many decimals to show
decimalCount?: number | string
// The thousand separator character
thousand?: string
};
# 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
Types
type FuzzySearchOptions = {
caseSensitive: boolean
};
# 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
Convert Hexadecimal into a number (eg. b4 => 180)
@returns : Numeric representation of the hex code
Examples
hexToNumber('ba'); // --> 186
# 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)
Is the given argument a boolean
@returns : Whether the argument a Boolean or not
Examples
isBoolean(false); // --> true
isBoolean('string'); // --> false
# 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)
Is the given argument is a finite Number
@returns : Whether the argument a finite number or not
Examples
isNumber(123); // --> true
isNumber(Infinity); // --> false
isNumber('123'); // --> false
# 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)
Is the given argument of type String
@returns : Whether the argument a plain object or not
Examples
class Obj {}
isObject({}); // --> true
isObject(new Obj()); // --> true
isObject('123'); // --> false
# isString
isString(x: unknown): boolean (x is string)
Is the given argument of type String
@returns : Whether the argument a string or not
Examples
isString('string'); // --> true
isString(123); // --> false
# 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
Types
type KebabCaseSettings = PhrasifySettings;
# leadingZero
leadingZero(num: string | number, len?: number): string
Makes sure a given number is a certain length and fills excess space with zeroes (0)
@returns : The given number as a string padded with zeroes to match the given min length
Examples
leadingZero(1); // --> '01'
leadingZero(123); // --> '123'
leadingZero(123, 5); // --> '00123'
# 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
Limit a number to a certain range defined by Minimum and a Maximum
@returns : The number limited to the min/max boundaries
Examples
minMax(5, 10, 20); // --> 10
minMax(15, 10, 20); // --> 15
minMax(25, 10, 20); // --> 20
# numberToHex
numberToHex(num: number): string
Convert a number to a Hexadecimal representation (eg. 180 => b4)
@returns : Hex representation of the given number
Examples
numberToHex(180); // --> 'b4'
# pascalCase
pascalCase(input: string, settings?: PascalCaseSettings): string
Transform a string into a PascalCased word (eg. 'pascal case' -> 'PascalCase')
@returns : The formatted string
Examples
pascalCase('data-value2-input'); // --> DataValue2input
pascalCase('XML data input'); // --> XmlDataInput
// With settings
const settings = { abbr: true, numbers: true };
pascalCase('data-VALUE2-input', settings); // --> DataVALUE2Input
Types
type PascalCaseSettings = Omit<CamelCaseSettings, 'upper'>;
# 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
Types
type PhrasifySettings = {
// Separate numbers from words?
numbers?: boolean
};
# popAtIndex
popAtIndex<T>(list: T[], index: number): T | undefined
Removes and returns an entry from a given array, at a designated index position.
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 formatted string
Examples
function action(name, callback) { ... callback(); }
action = promisefy(action);
action
.then(() => 'all good')
.catch(() => 'Something went wrong');
Types
type NodeLikeCallback = (err?: string | Error | null, data?: unknown) => unknown;
type PromisefiedFunction = (args: any[]) => Promise<any>;
type PromisefyCallback = (args: any[]) => any;
# 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
@returns : A random generated id of a specified length
Examples
randomCryptoId(); // --> eg. 'efuc6f1n4xf'
randomCryptoId(20); // --> eg. '3vsmrbxlh9at0vhcsf1xh'
# randomHexColor
randomHexColor(): string
Generate a random HEX color
@returns : A random hex color
Examples
randomHexColor(); // --> eg. #f42c71
# 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]
Generate a random RGB color
@returns : An Array with random R G B values
Examples
randomRGBColor(); // --> eg. [169, 100, 52]
# 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
Types
type RGBTuple = [red: number, green: number, blue: number, alpha?: number];
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
Types
type RGBTuple = [red: number, green: number, blue: number, alpha?: number];
# 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
Types
type SnakeCaseSettings = PhrasifySettings;
# 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 <---
Types
type TruncateSettings = {
// What ending to give the truncated string (default is "...")
end?: string
// Max length of the given string
maxLength?: number
};
# uniqueArray
uniqueArray<T>(arr: ArrayLike | Iterable): 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)