@tempots/std

tempotempotsframeworkstdlibrary
Std library for TypeScript. Natural complement to the Tempo libraries.

std package

Functions

Function

Description

allElements(arr, predicate)

Checks if all elements in an array satisfy a given predicate.

angleDifference(a, b, turn)

Calculates the minimum difference between two angles in degrees.

anyElement(arr, predicate)

Checks if any element in the array satisfies the given predicate.

applyArrayDiffOperations(operations, start)

Applies a series of operations to an array and returns the modified array.

areArraysEqual(a, b, equality)

Checks if two arrays are equal based on a custom equality function.

arrayDiffOperations(from, to, getKey)

Calculates the difference operations between two arrays based on a key function.

arrayHasValues(arr)

Checks if an array has values.

arrayHead(arr)

Returns the first element of an array, or undefined if the array is empty.

arrayOfIterableIterator(it)

Converts an IterableIterator to an array.

arrayTail(arr)

Returns a new array containing all elements of the input array except for the first element.

biAbs(x)

Returns the absolute value of a bigint.

biCeilDiv(x, y)

Calculates the ceiling division of two BigInt numbers.

biCompare(x, y)

Compares two BigInt values and returns a number indicating their relative order.

biFloorDiv(x, y)

Divides two BigInt numbers and returns the largest integer less than or equal to the quotient.

biGcd(x, y)

Calculates the greatest common divisor (GCD) of two BigInt numbers.

biIsEven(x)

Checks if a given bigint is even.

biIsNegative(x)

Checks if a given bigint is negative.

biIsOdd(x)

Checks if a given bigint is odd.

biIsOne(x)

Checks if a given bigint is equal to 1n.

biIsPositive(x)

Checks if a bigint is positive.

biIsPrime(x)

Checks if a given number is prime.

biIsZero(x)

Checks if a given bigint is zero.

biLcm(x, y)

Calculates the least common multiple (LCM) of two BigInt numbers.

biMax(x, y)

Returns the maximum of two BigInt values.

biMin(x, y)

Returns the minimum of two BigInt values.

biNextPrime(x)

Finds the next prime number greater than the given number.

biPow(x, y)

Calculates the power of a bigint number.

biPrevPrime(x)

Returns the previous prime number less than the given number. Throws an error if there is no previous prime.

canonicalizeNewlines(value)

Replaces occurrances of \r\n, \n\r, \r with \n

capitalize(s)

capitalize returns a string with the first character convert to upper case.

capitalizeWords(value, whiteSpaceOnly)

Capitalize the first letter of every word in value. If whiteSpaceOnly is set to true the process is limited to whitespace separated words.

ceilTo(v, decimals)

Rounds a number up to the specified number of decimals.

chunkString(s, len)

Returns an array of string whose elements are equally long (using len). If the string s is not exactly divisible by len the last element of the array will be shorter.

clamp(value, min, max)

clamp restricts a value within the specified range.

clampInt(value, min, max)

Clamps a number to a specified range and returns an integer value.

clampSym(v, max)

Like clamp but you only pass one argument (max) that is used as the upper limit and the opposite (additive inverse or -max) as the lower limit.

collapseText(value)

It cleans up all the whitespaces in the passed value. collapse does the following: - remove trailing/leading whitespaces - within the string, it collapses seqeunces of whitespaces into a single space character For whitespaces in this description, it is intended to be anything that is matched by the regular expression \s.

compareArrays(a, b, comparef, shorterFirst)

Compares two arrays based on their lengths and element values.

compareCaseInsensitive(a, b)

Compares two strings ignoring their case.

compareNumbers(a, b)

It returns the comparison value (an integer number) between two float values.

compareStrings(a, b)

It compares to string and it returns a negative number if a is inferior to b, zero if they are the same, or otherwise a positive non-sero number.

concatArrays(arrs)

Concatenates multiple arrays into a single array.

containsAllText(s, tests)

containsAllText returns true if s contains all of the strings in tests

containsAllTextCaseInsensitive(s, tests)

containsAllTextCaseInsensitive returns true if s contains all of the strings in tests regardless of the text case

containsAnyText(s, tests)

containsAnyText returns true if s contains any of the strings in tests

containsAnyTextCaseInsensitive(s, tests)

containsAnyTextCaseInsensitive returns true if s contains any of the strings in tests regardless of the text case

countStringOccurrences(s, test)

Return the number of occurrences of test in s.

createFilledArray(length, value)

Creates a new array with the specified length and fills it with the provided value.

curryLeft(f)

Curries a function from left to right.

dasherize(s)

dasherize replaces all the occurrances of _ with -

decodeBase64(s)

Decodes a base64 encoded string.

deepEqual(a, b)

Checks if two values are equal by comparing their contents.

deleteFirstFromString(value, toremove)

If present, it removes the first occurrence of toremove from value.

deleteStringAfter(value, toremove)

If present, it removes the toremove text from the end of value.

deleteStringBefore(value, toremove)

If present, it removes the toremove text from the beginning of value.

deleteSubstring(value, toremove)

If present, it removes all the occurrences of toremove from value.

ellipsis(s, maxlen, symbol)

ellipsis truncates s at len maxlen replaces the last characters with the content of symbol.

ellipsisMiddle(s, maxlen, symbol)

Same as ellipsis but puts the symbol in the middle of the string and not to the end.

encodeBase64(s)

Encodes a string to base64.

filterArray(arr, predicate)

Filters the elements of an array based on a predicate function.

filterCharcodes(s, predicate)

Same as filterCharcodes but predicate operates on integer char codes instead of string characters.

filterChars(s, predicate)

filterString applies predicate character by character to s and it returns a filtered version of the string.

filterMapArray(arr, f)

Applies a mapping function to each element of an array and returns a new array containing the mapped values, excluding any null or undefined values.

filterNullsFromArray(arr)

Filters out null and undefined values from an array.

flatMapArray(arr, f)

Applies a mapping function to each element of an array and flattens the result.

flattenArray(arr)

Flattens a two-dimensional array into a one-dimensional array.

floorTo(v, decimals)

Rounds a number down to the specified number of decimals.

foldLeftArray(arr, f, b)

Applies a function to each element of an array, accumulating the result from left to right.

forEachElement(arr, f)

Applies a function to each element in an array.

generateArray(length, f)

Generates an array of values by applying a function to each index.

generateSequenceArray(length, startAt)

Generates an array of numbers in a specified range.

humanize(s)

Works the same as underscore but also replaces underscores with whitespaces.

identity(v)

Returns the input value as is.

ifEmptyString(value, alt)

ifEmpty returns value if it is neither null or empty, otherwise it returns alt

interpolate(a, b, t)

interpolate returns a value between a and b for any value of t (normally between 0 and 1).

interpolateAngle(a, b, t, turn)

Interpolates values in a polar coordinate system looking for the narrowest delta angle. It can be either clock-wise or counter-clock-wise.

interpolateAngleCCW(a, b, t, turn)

Interpolates values in a polar coordinate system always in counter-clock-wise direction.

interpolateAngleCW(a, b, t, turn)

Interpolates values in a polar coordinate system always in clock-wise direction.

interpolateWidestAngle(a, b, t, turn)

Interpolates values in a polar coordinate system looking for the wideset delta angle. It can be either clock-wise or counter-clock-wise.

isAlpha(s)

Checks if s contains only (and at least one) alphabetical characters.

isAlphaNum(value)

isAlphaNum returns true if the string only contains alpha-numeric characters.

isArrayEmpty(arr)

Checks if an array is empty.

isBreakingWhitespace(value)

Checks if a string contains any breaking whitespace characters.

isDigitsOnly(value)

isDigitsOnly returns true if the string only contains digits.

isEmptyObject(obj)

Checks if an object is empty. An object is considered empty if it has no own enumerable properties.

isEmptyString(value)

isEmpty returns true if either value is null or is an empty string.

isJSONArray(value)

Checks if the value is a JSON array.

isJSONObject(value)

Checks if the value is a JSON object.

isJSONPrimitive(value)

Checks if the value is a JSON primitive.

isLowerCase(value)

Returns true if the value string is composed of only lower cased characters or case neutral characters.

isObject(obj)

Checks if the given value is an object.

isSpaceAt(s, pos)

Checks if the character at the specified position in a string is a whitespace character.

isUpperCase(value)

Returns true if the value string is composed of only upper cased characters or case neutral characters.

joinArrayWithConjunction(arr, conjunction, separator)

Joins an array of values into a string using a conjunction and separator.

jsQuote(s, prefer)

Quotes a string for use in JavaScript code. If the string contains a newline character, it will be quoted using backticks. Otherwise, it will be quoted using single quotes (') or double quotes (") based on the prefer parameter.

looseEqual(a, b)

Checks if two values are loosely equal.

lowerCaseFirst(value)

Convert first letter in value to lower case.

lpad(s, char, length)

Pads a string on the left with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is.

mapArray(arr, f)

Applies a function to each element of an array and returns a new array with the results.

mapChars(callback, value)

It maps a string character by character using callback.

mapRegExp(subject, pattern, f)

Map the function f on each occurance matched by the pattern.

memoize(f)

Memoizes the result of a function and returns a new function that caches the result. The cached result is returned if available, otherwise the original function is called and the result is cached for future invocations.

mergeObjects(a, b)

Merges two objects together.

nearEqualAngles(a, b, turn, tollerance)

number numbers can sometime introduce tiny errors even for simple operations. nearEqualAngles compares two angles (default is 360deg) using a tiny tollerance (last optional argument). By default the tollerance is defined as EPSILON.

nearEquals(a, b, tollerance)

number numbers can sometime introduce tiny errors even for simple operations. nearEquals compares two floats using a tiny tollerance (last optional argument). By default it is defined as EPSILON.

nearZero(n, tollerance)

nearZero finds if the passed number is zero or very close to it. By default EPSILON is used as the tollerance value.

objectEntries(obj)

Returns an array of entries (key-value pairs) from the given object.

objectFromEntries(entries)

Creates an object from an array of entries.

objectKeys(obj)

Returns an array of keys from the given object.

objectValues(obj)

Returns an array of values from the given object.

quote(s, quoteChar)

Returns a quoted version of the input string.

randomString(value, length)

Returns a random substring from the value argument. The length of such value is by default 1.

randomStringSequence(alphabet, length)

Returns a random sampling of the specified length from the seed string.

randomStringSequenceBase64(length)

Like randomSequence, but automatically uses the base64 sequence as the seed string.

rankArray(array, compare, incrementDuplicates)

Assigns ranks to the elements in the array based on the provided compare function. The ranks are assigned in ascending order, with the lowest value receiving a rank of 0. If there are duplicate values, the rank of the duplicates can be incremented or not based on the incrementDuplicates parameter.

removeAllFromArray(arr, item)

Removes all occurrences of an item from an array.

removeAllFromArrayByPredicate(arr, predicate)

Removes all occurrences in an array that satisfy the given predicate.

removeObjectFields(ob, fields)

Removes specified fields from an object and returns a new object without those fields.

removeOneFromArray(arr, item)

Removes the first occurrence of an item from an array.

removeOneFromArrayByPredicate(arr, predicate)

Removes the first occurrence in an array that satisfy the given predicate.

repeatString(s, times)

repeatString builds a new string by repeating the argument s, n times.

replaceAll(subject, placeholder, replacement)

Replaces all occurrances of placeholder in subject with the value replacement.

reverseString(s)

Returns a new string whose characters are in reverse order.

root(base, index)

Computes the nth root (index) of base.

roundTo(f, decimals)

Rounds a number to the specified number of decimals.

rpad(s, char, length)

Pads a string on the right with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is.

sameObjectKeys(a, b)

Checks if two objects have the same keys.

sign(value)

sign returns -1 if value is a negative number, 1 otherwise.

sleep(ms, { abortSignal })

Sleep for a given number of milliseconds.

smartQuote(s, prefer)

Converts a string in a quoted string.

sortArray(arr, compare)

Sorts an array in place using the provided compare function.

splitStringOnce(s, separator)

It only splits on the first occurrance of separator.

splitStringOnFirst(s, find)

Splits a string into two parts based on the first occurrence of a specified substring. If the substring is found, returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, returns an array with a single element: the original string.

splitStringOnLast(s, find)

Splits a string into two parts at the last occurrence of a specified substring. If the substring is found, the function returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, the function returns an array with a single element, which is the original string.

strictEqual(a, b)

Checks if two values are strictly equal.

stringContains(s, test)

textContains returns true if s contains one or more occurrences of test.

stringEndsWith(s, end)

Checks if a string ends with a specified suffix.

stringEndsWithAny(s, values)

Returns true if s ends with any of the values in values.

stringHasContent(value)

Returns true if value is not null and contains at least one character.

stringHashCode(value, seed)

Calculates the hash code for a given string.

stringsDifferAtIndex(a, b)

Compares strings a and b and returns the position where they differ. If the strings are equal, it returns -1.

stringStartsWith(s, start)

Checks if a string starts with a specified substring.

stringStartsWithAny(s, values)

Returns true if s starts with any of the values in values.

stringToCharcodes(s)

It transforms a string into an Array of char codes in integer format.

stringToChars(s)

It transforms a string into an Array of characters.

substringAfter(value, searchFor)

substringAfter searches for the first occurrance of searchFor and returns the text after that. If searchFor is not found, an empty string is returned.

substringAfterLast(value, searchFor)

substringAfterLast searches for the last occurrance of searchFor and returns the text after that. If searchFor is not found, an empty string is returned.

substringBefore(value, searchFor)

substringBefore searches for the first occurrance of searchFor and returns the text before that. If searchFor is not found, an empty string is returned.

substringBeforeLast(value, searchFor)

substringBeforeLast searches for the last occurrance of searchFor and returns the text before that. If searchFor is not found, an empty string is returned.

surroundString(s, left, right)

Surrounds a string with the contents of left and right. If right is omitted, left will be used on both sides

textContainsCaseInsensitive(s, test)

textContainsCaseInsensitive returns true if s contains one or more occurrences of test regardless of the text case.

textEndsWithAnyCaseInsensitive(s, values)

Compares a string s with many values and see if one of them matches its end ignoring their case.

textEndsWithCaseInsensitive(s, end)

Checks if a string ends with another string in a case-insensitive manner.

textStartsWithAnyCaseInsensitive(s, values)

Compares a string s with many values and see if one of them matches its beginning ignoring their case.

textStartsWithCaseInsensitive(s, start)

Checks if a string starts with another string in a case-insensitive manner.

textToLines(s)

Returns an array of string split by line breaks.

toHex(num, length)

Converts a number to its hexadecimal representation.

trimChars(value, charlist)

trimChars removes from the beginning and the end of the string any character that is present in charlist.

trimCharsLeft(value, charlist)

trimCharsLeft removes from the beginning of the string any character that is present in charlist.

trimCharsRight(value, charlist)

trimCharsRight removes from the end of the string any character that is present in charlist.

trimStringSlice(value, index, length)

Removes a slice from index to index + length from value.

underscore(s)

underscore finds UpperCase characters and turns them into LowerCase and prepends them with a whtiespace. Sequences of more than one UpperCase character are left untouched.

uniqueByPrimitive(values, predicate)

Returns an array of distinct elements from the input array based on the provided predicate.

uniquePrimitives(values)

Returns an array containing only the distinct primitive values from the input array.

upperCaseFirst(value)

Convert first letter in value to upper case.

widestAngleDifference(a, b, turn)

Calculates the widest angle difference between two angles.

wrap(v, min, max)

Passed two boundaries values (min, max), wrap ensures that the passed value v will be included in the boundaries. If the value exceeds max, the value is reduced by min repeatedely until it falls within the range. Similar and inverted treatment is performed if the value is below min.

wrapCircular(v, max)

Similar to wrap, it works for numbers between 0 and max.

wrapColumns(s, columns, indent, newline)

wrapColumns splits a long string into lines that are at most columns long. Individual words whose length exceeds columns are not split.

wrapLine(s, columns, indent, newline)

Wraps a string into multiple lines based on the specified number of columns, indentation, and newline character.

Interfaces

Interface

Description

JSONObject

Represents a JSON object.

Variables

Variable

Description

AsyncResult

A set of utility functions for working with AsyncResult.

EPSILON

Constant value employed to see if two number values are very close.

Result

Utility functions for working with Result types.

Validation

Utility functions for working with Validation types.

Type Aliases

Type Alias

Description

ArrayDiffOperations

Represents the different operations that can be performed on an array.

AsyncFailure

Represents a failure result.

AsyncResult

Represents the result of an asynchronous operation that can be in one of the following states: - NotAsked: The operation has not been requested yet. - Loading: The operation is currently in progress. - Success: The operation has completed successfully and contains a value of type V. - Failure: The operation has completed with an error and contains an error of type E.

AsyncSuccess

Represents a successful result.

Compare

Represents a function that compares two values of type T and returns a number. The returned number indicates the relative order of the two values: - A negative number if a is less than b. - Zero if a is equal to b. - A positive number if a is greater than b.

Failure

Represents a failure result.

FilterTuple

Filters out elements from a tuple that are equal to the specified type.

FirstArgument

Extracts the first argument type from a function type.

Fun0

Represents a function that takes no arguments and returns a value of type R.

Fun1

Represents a function that takes one argument of type A and returns a value of type R.

Fun2

Represents a function that takes two arguments of types A and B, and returns a value of type R.

Fun3

Represents a function that takes three arguments of types A, B, and C, and returns a value of type R.

Fun4

Represents a function that takes four arguments of types A, B, C, and D, and returns a value of type R.

Fun5

Represents a function that takes five arguments of types A, B, C, D, and E, and returns a value of type R.

Fun6

Represents a function that takes six arguments of types A, B, C, D, E, F and returns a value of type R.

Id

Represents an identity type that preserves the properties of the original type.

IndexKey

Represents a key type that can be used to index any object.

Invalid

Represents an invalid value with an associated error.

JSONArray

Represents an array of JSON values.

JSONPrimitive

Represents a JSON primitive value. It can be a string, boolean, number, or Nothing (null or undefined).

JSONValue

Represents a JSON value, which can be a primitive, an object, or an array.

Loading

Represents a loading state in an asynchronous result.

Maybe

Represents a type that can either hold a value of type T or be undefined.

Merge

Represents the type resulting from merging two types A and B. The resulting type is the intersection of A and B.

NotAsked

Represents the state when a result has not been requested yet.

Nothing

Represents a value that can be either undefined or null.

PartialBy

Creates a new type by making the specified key K of T optional.

Primitive

Represents a primitive value that can be of type string, boolean, number, null, or undefined.

PromiseResult

Represents a promise that resolves to a Result type.

PromiseValidation

Represents a promise that resolves to a Validation object.

RequiredBy

Creates a new type by making the specified key K of T required.

Result

Represents a result that can either be a success or a failure.

SplitLiteral

Splits a string literal type T by a specified delimiter SplitBy. Returns a tuple containing the split parts of the string.

SplitLiteralToUnion

Converts a string literal type T into a union type by splitting it using the specified delimiter SplitBy.

Success

Represents a successful result.

TupleToUnion

Converts a tuple type to a union type.

Valid

Represents a valid result.

Validation

Represents a type that can either be Valid or Invalid.