Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
@sandstreamdev/std
Advanced tools
Modern library of statically-typed modular functions for daily use in JavaScript and TypeScript projects.
npm install @sandstreamdev/std
Checks if the given array is present and it is not empty (contains at least one element).
<T>(xs?: T[]) => boolean
any([]);
// ⇒ false
any([1, 2, 3]);
// ⇒ true
Checks if the given arguments are all Arrays
.
<T>(...xs: T[]) => boolean
are([2, 3]);
// ⇒ true
are([1, 2, 3], []);
// ⇒ true
are([1, 2, 3], 8, [1, 3], "test");
// ⇒ false
Splits the given array into an array of chunks of up to the given length.
(count: number) => <T>(xs: T[]) => T[] | T[][]
chunk(2)(['a', 'b', 'c', 'd']);
// ⇒ [['a', 'b'], ['c', 'd']]
chunk(3)(['a', 'b', 'c', 'd']);
// ⇒ [['a', 'b', 'c'], ['d']]
Computes a set difference between the two given arrays.
<T>(xs: T[], ys: T[]) => T[]
difference([1, 2, 3, 4, 5, 6], [2, 4]);
// ⇒ [1, 3, 5, 6]
Checks if two arrays are not equal.
<T>(xs?: T[], ys?: T[]) => boolean
differs([1, 2, 3], [1, 2]);
// ⇒ true
differs([1, 2, 3], [1, 2, 3]);
// ⇒ false
Lists all the duplicated values in the given array.
<T>(xs: T[]) => T[]
duplicates([1, 2, 3, 4, 3, 4, 3, 6]);
// ⇒ [3, 4, 3]
Empty array.
unknown[]
empty;
// ⇒ []
Takes exactly the given count of elements.
(count: number) => <T>(xs: T[]) => T[]
exact(5)([1, 2, 3]);
// ⇒ [1, 2, 3, undefined, undefined]
exact(2)([1, 2, 3]);
// ⇒ [1, 2]
Filters out the given value.
<T>(y: T) => (xs: T[]) => T[]
except(2)([1, 2, 3, 4, 5]);
// ⇒ [1, 3, 4, 5]
except(2)([1, 2, 2, 4, 2]);
// ⇒ [1, 4]
Filters the given array with the given predicate just like Array.filter but does it in-place thus mutates the original array.
<T>(f: (value: T, index: number, context: T[]) => boolean) => (xs: T[]) => T[]
const xs = [1, 2, 3, 4, 5, 6, 7];
const odd = x => x % 2 === 1;
const ys = filterInPlace(odd)(xs);
ys === xs;
// ⇒ true
ys;
// ⇒ [1, 3, 5, 7]
Finds an element by a predicate function within the given array, otherwise, it returns the given fallback value or undefined when fallback is not present.
<T>(predicate: (value: T, index: number, context: T[]) => boolean, fallback?: T) => (xs: T[]) => T
find(x => x > 2)([1, 2, 3, 5, 7]);
// ⇒ 3
find(x => x > 2)([1, 2, -3, -5, -7]);
// ⇒ undefined
Returns the first element or undefined when there are no elements in the given array.
<T>([x]: T[]) => T | undefined
first([1, 2, 3]);
// ⇒ 1
first([]);
// ⇒ undefined
Maps and flattens the result.
<T, TResult>(f: (value: T, index: number, context: T[]) => TResult[]) => (xs: T[]) => TResult[]
flatMap(text => [...text])(["test", "123"]);
// ⇒ ["t", "e", "s", "t", "1", "2", "3"]
Flattens the nested arrays by a single level.
<T>(xs: T[]) => T[]
flatten([1, [2, 3], 4, [5, 6]]);
// ⇒ [1, 2, 3, 4, 5, 6]
flatten([1, [2, [3, 6]], 4, [5, 6]]);
// ⇒ [1, 2, [3, 6], 4, 5, 6]
Inserts the given item to the array at a specific index.
(index: number) => <T>(item: T) => ([...xs]: T[]) => T[]
insert(0)('d')(['a', 'b', 'c']);
// ⇒ ['d', 'a', 'b', 'c']
insert(1)('d')(['a', 'b', 'c']);
// ⇒ ['a', 'd', 'b', 'c']
Finds common elements between both arrays.
<T>(xs: T[], ys: T[]) => T[]
intersection([1, 2, 3, 4, 5], [5, 5, 3, 2]);
// ⇒ [2, 3, 5]
Checks if the given argument is an array.
(value?: unknown) => boolean
is([1, 2, 3]);
// ⇒ true
is({ a: 5 });
// ⇒ false
Returns the last element or undefined when there are no elements in the given array.
<T>(xs: T[]) => T | undefined
last([1, 2, 3]);
// ⇒ 3
last([]);
// ⇒ undefined
Returns the number of elements in the given array.
<T>(xs: T[]) => number
length([true, 1]);
// ⇒ 2
length([1, 2, 3]);
// ⇒ 3
length([]);
// ⇒ 0
Checks if lengths of the given arrays differ.
<T1, T2>(a: T1[], b: T2[]) => boolean
lengthDiffers([1, 2, 3], [1, 2]);
// ⇒ true
lengthDiffers([6, 7], [1, 2]);
// ⇒ false
Maps the given array with the given functions.
<T>(...fs: ((x: T) => T)[]) => (xs: T[]) => T[]
map(x => x * x)([1, 2, 3]);
// ⇒ [1, 4, 9]
map(x => x * x, x => x + 1)([1, 2, 3]);
// ⇒ [2, 5, 10]
Returns the middle element or the right one when the number of elements is even.
<T>(xs: T[]) => T | undefined
midpoint([1, 2, 3, 4, 5]);
// ⇒ 3
midpoint([1, 2, 3, 4]);
// ⇒ 3
Computes minimum and maximum values of the given array in a single run.
(xs: number[]) => number[]
minMax([10, 5, 3, -5, -4, 23, 32, 8, 1, 0]);
// ⇒ [-5, 32]
minMax([1]);
// ⇒ [1, 1]
minMax([]);
// ⇒ [undefined, undefined]
Checks if the given array contains more than one element.
<T>(xs: T[]) => boolean
multiple([1, 2, 3]);
// ⇒ true
multiple([1, 2]);
// ⇒ true
multiple([1]);
// ⇒ false
multiple([]);
// ⇒ false
Checks if the given array is empty.
<T>(xs?: T[]) => boolean
none([]);
// ⇒ true
none([1, 2, 3]);
// ⇒ false
Partitions the given array to the ones that pass the given predicate function and the ones that do not. By convention of the Haskell's Data.Either, values that pass the predicate are placed at the right.
<T>(predicate: (x: T) => boolean) => (xs: T[]) => readonly [T[], T[]]
partition(x => x % 2 === 1)([1, 2, 3, 4, 5]);
// ⇒ [[2, 4], [1, 3, 5]])
Returns the given array without the last element.
<T>(xs: T[]) => T[]
pop([1, 2, 3, 4]); // ⇒ [1, 2, 3]
pop([]); // ⇒ []
Generates an array of numbers from 0 to n - 1.
(n: number) => number[]
range(3);
// ⇒ [0, 1, 2]
Removes an element at the given index from the given array.
(index: number) => <T>(xs: T[]) => T[]
removeAt(3)([1, 2, 3, 4, 5, 6])
// ⇒ [1, 2, 3, 5, 6]
Repeats the given element by the given count of times.
(count: number) => <T>(value: T) => T[]
repeat(3)("test");
// ⇒ ["test", "test", "test"]
Reverses the given array without mutating it (in contrast to Array.reverse).
<T>(xs: T[]) => T[]
reverse([1, 2, 3, 4, 5]);
// ⇒ [5, 4, 3, 2, 1]
Reverses the given array when enabled.
(enabled: boolean) => <T>(xs: T[]) => T[]
reverseIf(true)([1, 2, 3, 4, 5]);
// ⇒ [5, 4, 3, 2, 1]
reverseIf(false)([1, 2, 3, 4, 5]);
// ⇒ [1, 2, 3, 4, 5]
Returns the second element or undefined when there are less than two elements in the given array.
<T>(xs: T[]) => T | undefined
second([1, 2, 3, 4, 5]);
// ⇒ 2
second([1]);
// ⇒ undefined
second([]);
// ⇒ undefined
Returns the second to last element or undefined when there are less than two elements in the given array.
<T>(xs: T[]) => T | undefined
secondToLast([1, 2, 3, 4, 5]);
// ⇒ 4
secondToLast([1]);
// ⇒ undefined
secondToLast([]);
// ⇒ undefined
Shifts the given array to the left and circulates the elements back by modulo of the array's length.
(count: number) => <T>(xs: T[]) => T[]
shift(1)([1, 2, 3, 4, 5]);
// ⇒ [2, 3, 4, 5, 1]
shift(2)([1, 2, 3, 4, 5]);
// ⇒ [3, 4, 5, 1, 2]
shift(3)([1, 2, 3, 4, 5]);
// ⇒ [4, 5, 1, 2, 3]
Shuffles the given array in random order with Math.random as the default.
<T>(xs: T[], random?: () => number) => T[]
let i = 0;
const random = () =>
[
0.013606630487694282,
0.21052486239086554,
0.28299838254636556,
0.696161009199874,
0.32165320593537117
][i++];
shuffle([1, 2, 3, 4, 5], random); // => [3, 5, 4, 2, 1]
Shuffles the given array in-place in random order with Math.random as the default.
<T>(xs: T[], random?: () => number) => T[]
let i = 0;
const random = () =>
[
0.013606630487694282,
0.21052486239086554,
0.28299838254636556,
0.696161009199874,
0.32165320593537117
][i++];
shuffleInPlace([1, 2, 3, 4, 5], random); // => [3, 5, 4, 2, 1]
Checks if the given array contains exactly one element.
<T>(xs: T[]) => boolean
single([1]);
// ⇒ true
single([1, 2, 3]);
// ⇒ false
single([]);
// ⇒ false
Skips the given count of elements from the given array.
(count: number) => <T>(xs: T[]) => T[]
skip(2)([1, 2, 3, 4, 5]);
// ⇒ [3, 4, 5]
Returns a new array composed of tuples of the given sliding window length of consecutive elements.
(count: number) => <T>(xs: T[]) => T[][]
slidingWindow(2)([1, 2, 3, 4]);
// ⇒ [[1, 2], [2, 3], [3, 4]]
slidingWindow(3)([1, 2, 3, 4, 5]);
// ⇒ [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
slidingWindow(1)([1, 2, 3, 4, 5, 6]);
// ⇒ [[1], [2], [3], [4], [5], [6]]
Sorts the given array without mutating it.
<T>(f?: (a: T, b: T) => number) => (xs: T[]) => T[]
sort((a, b) => a - b)([13, 79, 20, 69, 44, 67, 18, 95, 26, 55]);
// ⇒ [13, 18, 20, 26, 44, 55, 67, 69, 79, 95]
Sums the given array of numbers.
(xs: number[]) => number
sum([1, 2, 3, 4, 5]);
// ⇒ 15
Takes up to a given count of elements.
(count: number) => <T>(xs: T[]) => T[]
take(2)([1, 2, 3, 4, 5]);
// ⇒ [1, 2]
take(10)([1, 2, 3, 4, 5]);
// ⇒ [1, 2, 3, 4, 5]
Returns unique elements of the given array.
<T>(xs: T[]) => T[]
unique([1, 2, 3, 4, 3, 4, 3, 6]);
// ⇒ [1, 2, 3, 4, 6]
Filters out duplicated values based on the result of the given key selector.
<T, TResult>(f: (x: T) => TResult) => (xs: T[]) => T[]
uniqueBy(({ id }) => id)([
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 1, value: 'c' }
])
// ⇒ [{ id: 1, value: 'c' }, { id: 2, value: 'b' }]
Zips the given arrays together into pairs.
(xs: unknown[], ys: unknown[]) => [unknown, unknown][]
zip([1, 2, 3], [4, 5, 6]);
// ⇒ [[1, 4],[2, 5],[3, 6]]
Zips the given arrays together into pairs.
<T>(...xs: T[][]) => T[][]
zipN([1, 2, 3], [4, 5, 6]);
// ⇒ [[1, 4], [2, 5], [3, 6]]
zipN([1, 2, 3], [4, 5, 6], [7, 8, 9]);
// ⇒ [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
zipN([1, 2], [4, 5, 6], [7, 8, 9]);
// ⇒ [[1, 4, 7],[2, 5, 8]]
Zips the given arrays together with the given function.
<T1, T2>(f?: (x: T1, y: T2) => [T1, T2]) => (xs: T1[], ys: T2[]) => [T1, T2][]
zipWith((x, y) => x * x + y)([1, 2, 3], [4, 5, 6]);
// ⇒ [5, 9, 15]
Makes the function run after the given period of not being called. Useful to delay input submission for auto-complete etc.
(f: F, wait: number) => (...args: unknown[]) => void
const f = () => console.log("Test");
const debounced = debounce(f, 2000);
debounced();
setTimeout(debounced, 1000);
setTimeout(debounced, 3000);
When awaited, delays the execution by the given number of milliseconds.
(duration: number) => Promise<unknown>
delay(2000)(() => console.log("Test"));
Runs the given tasks in a sequence.
<T>(tasks: Task<T>[]) => Promise<Awaited<T>[]>
const f = () => new Promise(resolve => setTimeout(resolve, 1000));
const g = () => new Promise(resolve => setTimeout(resolve, 2000));
sequence([f, g]).then(() => console.log("Done"));
Clamps the given date to the given date range.
(min: Date, max: Date) => (date: Date) => Date
const date = new Date("2019-06-15T13:54:33.232Z");
const min = new Date("2019-02-23T13:54:33.232Z");
const max = new Date("2019-03-13T13:54:33.232Z");
clamp(min, max)(date);
// => new Date("2019-03-13T13:54:33.232Z")
Clones the given Date object.
(date: Date) => Date
const date = new new Date("2019-04-24T13:54:33.232Z");
const cloned = clone(date);
cloned !== date && cloned.valueOf() === date.valueOf();
// ⇒ true
Computes a signed difference between two Date objects as milliseconds.
(a: Date, b: Date) => number
dateDiff(new Date("2017-01-01T13:00:00.000Z"), new Date("2017-01-01T12:00:00.000Z"));
// ⇒ 3600000
Checks if the given date is between the given date range (inclusive).
(from: Date, to: Date) => (date: Date) => boolean
dateInRange(new Date("2018-06-10T12:00:00.000Z"), new Date("2018-06-20T12:00:00.000Z"))(new Date("2018-06-15T12:00:00.000Z"));
// ⇒ true
Returns a local day range at a particular Date.
(date: Date) => Date[]
const date = new Date("2018-12-31T13:54:33.232Z");
dayRange(date);
// ⇒ [startOfDay(date), endOfDay(date)]
Returns an array of days in a particular months. Number of days in February varies if it is a leap year or not.
(leapYear: boolean) => [number, number, number, number, number, number, number, number, number, number, number, number]
daysInMonths(false);
// ⇒ [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
daysInMonths(true);
// ⇒ [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Calculates the number of days in a particular year. Varies by the leap year.
(year: number) => 366 | 365
daysInYear(2019);
// ⇒ 365
daysInYear(2020);
// ⇒ 366
Displays padded time string.
(source: [number, number, number], showSeconds: boolean) => string
displayTime([5, 12, 16], false);
// ⇒ 05:12
displayTime([5, 12, 16], true);
// ⇒ 05:12:16
Returns a local Date of an end of the day at a particular Date.
(date: Date) => Date
endOfDay(new Date("2018-12-31T13:54:33.232Z"));
// ⇒ new Date(new Date("2019-01-01T00:00:00.000Z").valueOf() + new Date("2018-12-31T13:54:33.232Z").getTimezoneOffset() * 60 * 1000)
Formats a given date as a simple YYYY-MM-DD string.
(date: Date) => string
formatDate(new Date("2019-02-24T01:12:34"));
// ⇒ "2019-02-24"
Formats a given date as a simple YYYY-MM-DD HH:MM(:SS) string.
(sourceDate: Date, showSeconds?: boolean) => string
formatDateTime(new Date("2019-02-24T01:12:34"));
// ⇒ "2019-02-24 01:12"
formatDateTime(new Date("2019-02-24T01:12:34"), true);
// ⇒ "2019-02-24 01:12:34"
Formats a duration in milliseconds to a padded time string.
(duration: number, showSeconds?: boolean) => string
formatDuration(26100000);
// ⇒ 07:15
formatDuration(26136000, true);
// ⇒ 07:15:36
Formats a given date as a simple HH:MM(:SS) string.
(date: Date, showSeconds?: boolean) => string
formatTime(new Date("2019-02-24T01:12:34"));
// ⇒ "01:12"
formatTime(new Date("2019-02-24T01:12:34"), true);
// ⇒ "01:12:34"
Converts the given day count to milliseconds.
(days: number) => number
fromDays(1);
// ⇒ 86400000
Converts the given hour count to milliseconds.
(hours: number) => number
fromHours(1);
// ⇒ 3600000
Converts the given minute count to milliseconds.
(minutes: number) => number
fromMinutes(1);
// ⇒ 60000
Converts the given second count to milliseconds.
(seconds: number) => number
fromSeconds(1);
// ⇒ 1000
Joins a date-time pair into a date-time string.
(date: string, time: string) => string
joinDateTime("2019-01-15", "13:54:33.232Z");
// ⇒ "2019-01-15T13:54:33.232Z"
Detects if a given year is a leap year.
(year: number) => boolean
leapYear(2020);
// ⇒ true
leapYear(2019);
// ⇒ false
Parses HH:MM string into hours and minutes.
(text?: string) => [number, number]
parseHourMinutePair("12:34");
// ⇒ [12, 34]
Splits a date-time string into a date-time pair.
(dateTimeString: string) => [string, string]
splitDateTime("2019-01-15T13:54:33.232Z");
// ⇒ ["2019-01-15", "13:54:33.232Z"]
Returns a local Date of a start of the day at a particular Date.
(date: Date) => Date
endOfDay(new Date("2019-01-01T13:54:33.232Z"));
// ⇒ new Date(new Date("2019-01-01T00:00:00.000Z").valueOf() + new Date("2019-01-01T13:54:33.232Z").getTimezoneOffset() * 60 * 1000)
Subtracts the given number of days from the given Date object.
(sourceDate: Date, numberOfDays: number) => Date
subtractDays(new Date("2019-01-15T13:54:33.232Z"), 1);
// ⇒ new Date("2019-01-14T13:54:33.232Z")
Extracts padded YYYY-MM-DD date string out of the given date object.
(date: Date) => string
toDate(new Date("2019-01-15T12:00:00.000Z"));
// ⇒ "2019-01-15"
Converts the given array of values into Dates using the Date constructor.
(xs: (string | number | Date)[]) => Date[]
toDates(["2019-01-15T13:54:33.232Z", new Date("2019-01-15T13:54:33.232Z").valueOf(), new Date("2019-01-15T13:54:33.232Z")]);
// ⇒ [new Date("2019-01-15T13:54:33.232Z"), new Date("2019-01-15T13:54:33.232Z"), new Date("2019-01-15T13:54:33.232Z")]
Converts milliseconds into days.
(milliseconds: number) => number
toDays(86400000);
// ⇒ 1
Converts milliseconds into hours.
(milliseconds: number) => number
toHours(3600000);
// ⇒ 1
Returns an ISO-compliant date-time string.
(x: Date) => string
toISO(new Date("2019-04-24T13:54:33.232Z"));
// ⇒ "2019-04-24T13:54:33.232Z"
Converts milliseconds into minutes.
(milliseconds: number) => number
toMinutes(60000);
// ⇒ 1
Converts milliseconds into seconds.
(milliseconds: number) => number
toSeconds(1000);
// ⇒ 1
Checks if the given date is present and it is valid.
(date?: unknown) => boolean
valid(new Date("2020-01-31T09:52:31.618Z"));
// ⇒ true
valid(new Date("2020-01-42:52:31.618Z"));
// ⇒ false
valid(new Date("test"));
// ⇒ false
valid(undefined);
// ⇒ false
Asserts given conditions.
(condition: boolean, callbackOrMessage?: (() => void) | string) => void;
export declare const throws: (f: () => void) => unknown | undefined;
export declare const assertNumber: (x?: unknown) => void;
export declare const assertInteger: (x?: unknown) => void;
export declare const assertByte: (x?: unknown) => void;
export declare const assertNormal: (x?: unknown) => void;
export declare const assertString: (x?: unknown, message?: string) => void;
export declare const assertIsDefined: (x?: unknown, message?: string) => void;
export default assert
assert(true === false);
// ⇒ TypeError("Assertion failed!")
Computes a deep difference between the two values (primitives, objects, arrays, etc.).
(obj1?: unknown, obj2?: unknown) => DiffResult;
export default diff
diff({ a: 1 }, { a: 2 });
// ⇒ { a: { data: [1, 2], type: '~' }}
Decodes the given Base64URL back into a string.
(text: string, context?: DecodeContext) => string
decode("PDw_Pz8-Pg");
// ⇒ "<<???>>"
Decodes the given Base64URL back into a byte array.
(text: string, context?: DecodeContext) => number[]
decodeBytes("w4Jnw6vCp20-bBsQfA");
// ⇒ [0xc2, 0x67, 0xeb, 0xa7, 0x6d, 0x3e, 0x6c, 0x1b, 0x10, 0x7c]
Encodes the given string into Base64URL.
(text: string, context?: EncodeContext) => string
encode("<<???>>");
// ⇒ "PDw_Pz8-Pg"
Encodes the given bytes into Base64URL.
(bytes: number[], context?: EncodeContext) => string
encodeBytes([0xc2, 0x67, 0xeb, 0xa7, 0x6d, 0x3e, 0x6c, 0x1b, 0x10, 0x7c]);
// ⇒ "w4Jnw6vCp20-bBsQfA"
Converts Base64 string into Base64URL one.
(base64: string) => string
fromBase64("PDw/Pz8+Pg==");
// ⇒ "PDw_Pz8-Pg"
Converts Base64URL string into Base64 one.
(base64Url: string) => string
toBase64("PDw_Pz8-Pg");
// ⇒ "PDw/Pz8+Pg=="
Converts a string to a byte array.
(byteString: string) => number[]
from("PQR");
// ⇒ [80, 81, 82]
Coverts a byte array into a string.
(bytes: number[]) => string
to([0x50, 0x51, 0x52]);
// ⇒ "PQR"
Checks if the given string is a valid Windows file name.
(name: string) => boolean
validName("my:file.png");
// ⇒ false
validName("file.txt");
// ⇒ true
validName("../file.txt");
// ⇒ false
validName("COM1");
// ⇒ false
Composes multiple functions into a higher-order one. Goes right to left.
<T, TResult>(...fs: ((x: T) => T)[]) => (x: T) => T
compose(x => x * x, x => x + 1)(3);
// ⇒ 16
Returns the given constant no matter the input.
<T>(x: T) => () => T
constant(3)("anything");
// ⇒ 3
Always return the given value.
<T>(x: T) => T
identity(5);
// ⇒ 5
identity("test");
// ⇒ "test"
Memoizes the function result so it is not computed for the same parameters. Uses deep equality.
<TResult>(f: (...xs: unknown[]) => TResult) => (...args: unknown[]) => TResult
const f = x => { console.log(x); return x + 1; };
const memoized = memoize(f);
memoized(5);
memoized(5);
memoized(5);
memoized(3);
Memoizes the function result so it is not computed for the same parameters. Uses shallow equality.
<TResult>(f: (...xs: unknown[]) => TResult) => (...args: unknown[]) => TResult
const f = ({ x }) => { console.log(x); return x + 1; };
const memoized = memoizeShallow(f);
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 3 });
Memoizes the function result so it is not computed for the same parameters. Uses the given equality function.
<T>(equals: (x: T[], y: T[]) => boolean) => <TResult>(f: (...xs: T[]) => TResult) => (...args: T[]) => TResult
const f = ({ x }) => { console.log(x); return x + 1; };
const memoized = memoizeWith((a, b) => a.x === b.x)(f);
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 3 });
It does exactly nothing.
() => void
noOp("anything");
// ⇒ undefined
Inverts the given function result.
(f: (...xs: unknown[]) => unknown) => (...args: unknown[]) => boolean
not(x > 10)(15);
// ⇒ true
Pipes an input through given functions.
<T>(...fs: ((x: T) => T)[]) => (x: T) => T
pipe(x => x * x, x => x + 1)(3);
// ⇒ 10
Runs the given function only when the condition is met.
(predicate: (...xs: unknown[]) => boolean) => (action: (...xs: unknown[]) => unknown) => (...args: unknown[]) => unknown
when(x => x > 0)(x => console.log(x))(5);
when(x => x > 0)(x => console.log(x))(-3);
Runs the given function only when the condition is exactly true.
(action: (...xs: unknown[]) => unknown) => (...args: unknown[]) => unknown
whenTrue(x => console.log(x))(false);
when(x => x > 0)(x => console.log(x))(true);
Checks if the given argument is an array.
(x?: unknown) => boolean
array([1, 2, 3]);
// ⇒ true
array({ a: 1 });
// ⇒ false
Checks if the given value is a boolean.
(x?: unknown) => x is boolean
boolean(false); // ⇒ true
boolean(1); // ⇒ false
Checks if the given value is a byte.
(x?: unknown) => boolean
byte(128);
// ⇒ true
byte(325);
// ⇒ false
byte(65.5);
// ⇒ false
Checks if the given value is a Date object.
(x?: unknown) => boolean
date(new Date());
// ⇒ true
date(123);
// ⇒ false
Checks if the given value is defined.
(x?: unknown) => boolean
defined(undefined);
// ⇒ false
defined(null);
// ⇒ true
defined(0);
// ⇒ true
defined({ a: 1 });
// ⇒ true
Checks if the given value is a function.
(x?: unknown) => x is Function
_function(x => x + 5);
// ⇒ true
Checks if the given value is an integer.
(x?: unknown) => boolean
integer(5);
// ⇒ true
integer(32.5);
// ⇒ false
Checks and asserts the given value is not null or undefined.
<T>(val: T) => val is NonNullable<T>
nonNullable(null);
// ⇒ false
nonNullable(undefined);
// ⇒ false
nonNullable(false);
// ⇒ true
nonNullable({ a: 1 });
// ⇒ true
Checks if the given value is a number in a normal range [0, 1].
(x?: unknown) => boolean
normal(0.75);
// ⇒ true
normal(-1);
// ⇒ false
normal(2.5);
// ⇒ false
Checks if the given value is a number.
(x?: unknown) => boolean
number(0 / 0);
// ⇒ false
number(15.6);
// ⇒ true
Checks if the given value is an object.
(x?: unknown) => boolean
object({ a: 1, b: 2 });
// ⇒ true
object([1, 2, 3]);
// ⇒ false
Checks if the given value is a string.
(x?: unknown) => x is string
string("Test");
// ⇒ true
string(['T', 'e', 's', 't']);
// ⇒ false
Adds two values.
(a: number, b: number) => number
add(3, 5);
// ⇒ 8
Calculates the average of the given array of numbers.
(xs?: number[]) => number
average([2, 4, 15]);
// ⇒ 7
Finds the nearest power of two greater or equal to the given value.
(x: number) => number
ceilToNearestPowerOfTwo(345);
// ⇒ 512
Clamps the given value to the given range.
(min: number, max: number) => ((x: number) => number)
clamp(0, 10)(5);
// ⇒ 5
clamp(0, 10)(-5);
// ⇒ 0
clamp(0, 10)(15);
// ⇒ 10
Clamps the given value to the [0, 1] range.
(x: number) => number
clampNormal(0.5);
// ⇒ 0.5
clampNormal(-0.5);
// ⇒ 0
clampNormal(1.5);
// ⇒ 1
Clamps the given value to the [0, 100] range.
(x: number) => number
clampPercentage(50);
// ⇒ 50
clampPercentage(-50);
// ⇒ 0
clampPercentage(150);
// ⇒ 100
Calculates the absolute distance between given values.
(a: number, b: number) => number
delta(-3, 5);
// ⇒ 8
Checks if the given value is in the rectangular range of [0, width] and [0, height]
(width: number, height: number) => ((x: number, y: number) => boolean)
inRectangleRange(50, 100)(25, 50);
// ⇒ true
inRectangleRange(50, 100)(-25, 50);
// ⇒ false
Linearly interpolates two given values by the normal value of their distance.
(t: number) => ((a: number, b: number) => number)
lerp(0.5)(0, 10);
// ⇒ 5
lerp(0)(0, 10);
// ⇒ 0
lerp(1)(0, 10);
// ⇒ 10
Calculates the maximum by a given selector.
(f: (x: number) => number) => ((xs: number[]) => number)
maximumBy(({ age }) => age)([{ age: 13 }, { age: 20 }, { age: 7 }, { age: 18 }]);
// ⇒ { age: 20 }
Calculates the median of the values. If there is an even number of items, the average of the middle ones is returned.
(xs?: number[]) => number | undefined
median([-5, 3, 2, 29, 43]);
// ⇒ 3
Calculates the minimum and maximum value of the two given values.
([a, b]: [number, number]) => [number, number]
minMax([5, 3]);
// ⇒ [3, 5]
minMax([3, 5]);
// ⇒ [3, 5]
Checks if all the given values have the same sign.
(xs: number[]) => boolean
sameSign([-1, -2, -3]);
// ⇒ true
sameSign([1, 2, -3]);
// ⇒ false
Calculates the sign of the value and returns -1 for negative values, 1 for positive values and 0 for zeros.
(x: number) => number
sign(3);
// ⇒ 1
sign(-5);
// ⇒ 5
sign(0);
// ⇒ 0
sign(-0);
// ⇒ 0
Calculates the standard deviation of the given array of numbers.
(xs: number[], origin?: number) => number
standardDeviation([96, 81, 68, 79, 23, 13, 13, 59, 44, 86]);
// ⇒ (2 * Math.sqrt(10922 / 5)) / 3
Subtracts two values.
(a: number, b: number) => number
subtract(3, 5);
// ⇒ -2
Checks if the given object is present and it is not empty (contains at least one entry).
<T>(xs?: GenericObject<T>) => boolean
any({ a: 1, b: 2, c: 3 });
// ⇒ true
any({ });
// ⇒ false
any(null);
// ⇒ false
any(undefined);
// ⇒ false
Applies the given parameters to the given dictionary of functions.
<T>(fs: {
[index: string]: (...xs: T[]) => T;
}) => (...xs: T[]) => GenericObject<T>
const lower = text => text.toLowerCase();
const upper = text => text.toUpperCase();
apply({ lower, upper })("TeSt");
// ⇒ { lower: "test", upper: "TEST" }
Empty object.
GenericObject<unknown>;
export default empty
empty;
// ⇒ {}
Lists key-value pairs (entries) present in the given object.
ObjectEntries
entries({ a: 1, b: 2, c: 3 });
// ⇒ [["a", 1], ["b", 2], ["c", 3]]
Creates a 1 to 1 mapping of the given values as an object.
(...xs: string[]) => object
enumerable('TEST', 'X', 'Y');
// ⇒ { TEST: 'TEST', X: 'X', Y: 'Y' }
Checks if two objects are deeply equal.
(a: unknown, b: unknown) => boolean;
export default equalsDeep
equals({ a: 1 }, { a: 1 });
// ⇒ true
equals({ b: [1, 2] }, { b: [1, 2] });
// ⇒ true
Test if every element passes the given predicate.
<T>(f: (value: T, key: string, context: object) => boolean) => (xs: GenericObject<T>) => boolean
every(x => x >= 0)({ x: 5, y: 3, z: 0 });
// ⇒ true
every(x => x > 0)({ x: 5, y: 3, z: 0 });
// ⇒ false
Filters the given object with the given predicate.
<T>(f: (value: T, key: string, context: object) => boolean) => (xs: GenericObject<T>) => GenericObject<T>
filter(x => x % 2 !== 0)({ a: 1, b: 2, c: 3 });
// ⇒ { a: 1, c: 3 }
Searches the given object by the given predicate and returns the found value or undefined.
<T>(predicate: (value: T, key: string, context: object) => boolean) => (xs: GenericObject<T>) => T | undefined
find(({ x }) => x % 2 === 0)({ a: { x: 1 }, b: { x: 2 }, c: { x: 3 } });
// ⇒ { x: 2 }
Searches the given object by the given predicate and returns the found entry or undefined.
<T>(predicate: (value: T, key: string, context: GenericObject<T>) => boolean) => (xs: GenericObject<T>) => [string, T] | undefined
findEntry(({ x }) => x % 2 === 0)({ a: { x: 1 }, b: { x: 2 }, c: { x: 3 } });
// ⇒ ["b", { x: 2 }]
Searches the given object by the given predicate and returns the found key or undefined.
<T>(predicate: (value: T, key: string, context: object) => boolean) => (xs: GenericObject<T>) => string | undefined
findKey(({ x }) => x % 2 === 0)({ a: { x: 1 }, b: { x: 2 }, c: { x: 3 } });
// ⇒ "b"
Returns the first value in the given object. Follows the default object iteration order.
<T>(xs: GenericObject<T>) => T | undefined
first({ a: 1, b: 2, c: 3 });
// ⇒ 1
Flat maps the values of the given object.
<T, TResult>(f: (value: T, key: string, context: GenericObject<T>) => TResult[]) => (xs: GenericObject<T>) => TResult[]
flatMapValues(x => [x, x * 2])({ a: 1, b: 2, c: 3 });
// ⇒ [1, 2, 2, 4, 3, 6]
Creates an object from an array of key-value pairs (entries).
<T>(entries: [string, T][]) => Result<T>
fromEntries([["a", 1], ["b", 2], ["c", 3]]);
// ⇒ { a: 1, b: 2, c: 3 }
Groups the given array of values by the given key selector.
(selector: (x: unknown) => string) => (xs: unknown[]) => Result
groupBy(x => x % 2 == 0 ? "even" : "odd")([1, 2, 3, 4, 5, 6, 7]);
// ⇒ { even: [2, 4, 6], odd: [1, 3, 5, 7] }
Checks if the given key is present in the object.
(key: string) => (xs?: unknown) => boolean
hasKey("c")({ a: 1, b: 2, c: 3 });
// ⇒ true
Returns the last value in the given object. Follows the default object iteration order.
<T>(xs: GenericObject<T>) => T | undefined
last({ a: 1, b: 2, c: 3 });
// ⇒ 3
Returns the number of entries within the given object.
<T>(xs: GenericObject<T>) => number
length({ a: 1, b: 2, c: 3 });
// ⇒ 3
Maps the given object with the given function.
<T, TResult>(f: (value: T, key: string, context: object) => TResult) => (xs: GenericObject<T>) => GenericObject<TResult>
map(x => x ** 2)({ a: 1, b: 2, c: 3 });
// ⇒ { a: 1, b: 4, c: 9 }
Maps entries of the given object.
<T, TResult>(f: (value: T, key: string, context: object) => TResult) => (xs: GenericObject<T>) => [string, TResult][]
mapEntries(x => x ** 2)({ a: 1, b: 2, c: 3 });
// ⇒ [["a", 1], ["b", 4], ["c", 9]]
Transforms the object keys with the given function.
<T>(f: (value: T, key: string, context: object) => string) => (xs: GenericObject<T>) => GenericObject<T>
mapKeys((_, key) => key.toUpperCase())({ a: 1, b: 2, c: 3 });
// ⇒ { A: 1, B: 2, C: 3 }
Maps and returns an array of transformed object values.
<T, TResult>(f: (value: T, key: string, context: object) => TResult) => (xs: GenericObject<T>) => TResult[]
mapValues(x => x ** 2)({ a: 1, b: 2, c: 3 });
// ⇒ [1, 4, 9]
Merges two objects deeply.
(a: GenericObject, b: GenericObject) => GenericObject;
export default merge
merge({ a: 1, b: 3 }, {});
// ⇒ { a: 1, b: 3 }
merge({ a: 1, b: 3 }, { b: 7 });
// ⇒ { a: 1, b: 7 }
merge({ a: 1, b: 3 }, { b: { d: 8 } });
// ⇒ { a: 1, b: { d: 8 } }
merge({ a: 1, b: { c: 3 } }, { b: { d: 8 } });
// ⇒ { a: 1, b: { c: 3, d: 8 } }
Checks if the given object is empty.
<T>(xs?: GenericObject<T>) => boolean
none({});
// ⇒ true
none(null);
// ⇒ true
none({ a: 1 });
// ⇒ false
Test if any element passes the given predicate.
<T>(f: (value: T, key: string, context: object) => boolean) => (xs: GenericObject<T>) => boolean
some(x => x >= 4)({ x: 5, y: 3, z: 0 });
// ⇒ true
some(x => x < 0)({ x: 5, y: 3, z: 0 });
// ⇒ false
Sorts the given object by a comparator.
<T>(f: (a: T, b: T) => number) => (xs: GenericObject<T>) => GenericObject<T>
sort({ a: 3, b: 2, c: 3, d: -7, e: 13, f: 0, g: 8 });
// ⇒ {"d": -7,"f": 0,"b": 2,"a": 3,"c": 3,"g": 8,"e": 13}
Parses a query string into an object.
(xs?: string) => {
[index: string]: string | boolean;
}
parse("test&count=5");
// ⇒ { test: true, count: "5" }
Parses the given query string into an object using URLSearchParams.
(source: string) => Result
read("test&count=5");
// ⇒ { test: "", count: "5" }
Serializes the given object into a query string.
<T>(xs?: GenericObject<T>) => string
serialize({ test: true, value: "a string with spaces", missing: false });
// ⇒ "test&value=a%20string%20with%20spaces"
Checks if the given range is empty.
([min, max]: [number, number]) => boolean
empty([2, 2]);
// ⇒ true
empty([1, 5]);
// ⇒ false
Checks if the given ranges are equal.
([a, b]: [number, number], [c, d]: [number, number]) => boolean
equals([1, 2], [1, 2]);
// ⇒ true
equals([4, 3], [1, 2]);
// ⇒ false
Computes the signed length of the given range.
([min, max]: [number, number]) => number
length([3, 15]);
// ⇒ 12
length([1, 0]);
// ⇒ -1
Splits the given range into subranges by excluding the given used ranged.
(used: [number, number][], sourceRange?: number[]) => (range: [number, number]) => [number, number][];
export default split
split([[2, 3], [5, 7]]);
// ⇒ [[0, 2], [3, 5], [7, 10]]
Escapes regex string into proper regex.
(string: string) => string
escape("te.t").test("text");
// ⇒ false
Checks if the given string contains whitespace.
(x: string) => boolean
containsWhitespace("test string");
// ⇒ true
containsWhitespace("test");
// ⇒ false
Empty string.
""
empty();
// ⇒ ""
Transforms the first character to lowercase.
(text: string) => string
firstToLower("TeSt");
// ⇒ "teSt"
Transforms the first character to uppercase.
(text: string) => string
firstToUpper("teSt");
// ⇒ "TeSt"
Checks if the given substring is present in the source string.
(search: string) => (text: string) => boolean
includes("brown fox")("The quick brown fox jumps over the lazy dog");
// ⇒ true
includes("brown dog")("The quick brown fox jumps over the lazy dog");
// ⇒ false
Non-breaking space.
" "
nbsp;
// ⇒ " "
Checks if the given string is present and is not empty or all whitespace.
(x?: string) => boolean
nonEmpty("test with spaces");
// ⇒ true
nonEmpty(" ");
// ⇒ false
nonEmpty(null);
// ⇒ false
Checks if the given string starts with the given substring.
(prefix: string) => (xs: string) => boolean
startsWith("The")("The quick brown fox jumps over the lazy dog");
// ⇒ true
startsWith("Quick")("The quick brown fox jumps over the lazy dog");
// ⇒ false
Adds two vectors.
([x1, y1]: [number, number], [x2, y2]: [number, number]) => [number, number]
add([3, 5], [-1, 8]);
// ⇒ [2, 13]
Applies transformations to the given vector.
(space: {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}) => ([x, y]: [number, number]) => number[]
convertSpace(rotate(Math.PI))([2, 3]);
// ⇒ [-2, -3]
Calculates a cross product of the given vectors. Returns a scalar.
([a, b]: [number, number], [c, d]: [number, number]) => number
cross([3, 5], [-1, 8]);
// ⇒ 29
cross([3, 5], [-1, -8]);
// ⇒ -19
Calculates a dot product of the given vectors. Returns a scalar.
([a, b]: [number, number], [c, d]: [number, number]) => number
dot([3, 5], [-1, 8]);
// ⇒ 37
dot([3, 5], [-1, -8]);
// ⇒ -43
Calculates the length/magnitude of the given vector.
([x, y]: [number, number]) => number
length([3, 5]);
// ⇒ Math.sqrt(3 * 3 + 5 * 5)
Applies matrix transformation to the given vector.
({ a, b, c, d, e, f }: {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}, [x, y]: [number, number]) => number[]
mul(scale(4, 5), [2, 3]);
// ⇒ [8, 15]
Multiples two matrices.
(m1: {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}, m2: {
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
}) => {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}
multiply({ a: 1, c: 2, e: 3, b: 4, d: 5, f: 6 }, { a: 7, c: 8, e: 9, b: 10, d: 11, f: 12 });
// ⇒ { a: 27, b: 78, c: 30, d: 87, e: 36, f: 102 }
Normalizes the given vector. Returns [0, 0] vector for points.
(vector: [number, number]) => [number, number]
normalize([2, 3]);
// ⇒ [2 / length([2, 3]), 3 / length([2, 3])]
Reflects the given vector on the given surface.
(a: [number, number], v: [number, number]) => [number, number]
reflect([1, -2], [1, 0]);
// ⇒ [0.6, 0.8]
Creates a rotation matrix around given origin [0, 0] by default.
(angle?: number, cx?: number, cy?: number) => {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}
const angle = Math.PI;
const sine = Math.sin(angle);
const cosine = Math.cos(angle);
rotate(angle); // { a: cosine, b: sine, c: -sine, d: cosine, e: 0, f: 0 }
Creates a scale matrix.
(sx?: number, sy?: number) => {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}
scale(2, 3);
// ⇒ { a: 2, b: 0, c: 0, d: 3, e: 0, f: 0 }
Subtracts two vectors.
([x1, y1]: [number, number], [x2, y2]: [number, number]) => [number, number]
sub([3, 5], [-1, 8]);
// ⇒ [4, -3]
Composes a single transformation by matrix multiplication.
(...matrices: {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}[]) => {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}
const originX = 5;
const originY = 6;
const angle = Math.PI;
transform(translate(originX, originY), rotate(angle), translate(-originX, -originY));
// ⇒ rotate(Math.PI, originX, originY)
Creates a translation matrix.
(tx?: number, ty?: number) => {
a: number;
c: number;
e: number;
b: number;
d: number;
f: number;
}
translate(2, 3);
// ⇒ { a: 1, b: 0, c: 0, d: 1, e: 2, f: 3 }
Composes class name from truthy values with the support of string and objects.
(...xs: unknown[]) => string
classNames("test", { active: true, disabled: false, on: undefined });
// ⇒ "test active"
Stops propagation and prevents the default handler of the given event.
(event: {
preventDefault: () => void;
stopPropagation: () => void;
}) => boolean
const event = {
preventDefault: () => console.log("preventDefault"),
stopPropagation: () => console.log("stopPropagation")
};
cancel(event);
Tests if the current event seems like an intent to open a new tab. Useful for client-side navigation handling.
({ button, ctrlKey, metaKey, shiftKey }: {
button?: number;
ctrlKey?: boolean;
metaKey?: boolean;
shiftKey?: boolean;
}) => boolean
openInNewTabIntent({ ctrlKey: true });
// ⇒ true
Prevents the default handler of the given event.
(event: {
preventDefault: () => void;
}) => boolean
const event = {
preventDefault: () => console.log("preventDefault"),
stopPropagation: () => console.log("stopPropagation")
};
prevent(event);
Stops propagation of the given event.
(event: {
stopPropagation: () => void;
}) => boolean
const event = {
preventDefault: () => console.log("preventDefault"),
stopPropagation: () => console.log("stopPropagation")
};
stop(event);
Thanks goes to these wonderful people (emoji key):
sandstreamdevelopment 💼 💵 🤔 | Przemysław Zalewski 💻 🤔 | jakubbogacz 🤔 👀 | Marek Rozmus 👀 | Paweł 💻 | Krystian Boruciński 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!
FAQs
Modern library of statically-typed modular functions for daily use in JavaScript and TypeScript projects.
We found that @sandstreamdev/std demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.