migrate from elyukai/optolith-client

This commit is contained in:
Lukas Obermann
2024-10-04 20:11:05 +02:00
commit 2d57c024dd
46 changed files with 6006 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
name: Node.js Package
on:
push:
tags:
- v[0-9]+.[0-9]+.[0-9]+*
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- run: npm test
publish-npm:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- run: npm run build
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
+3
View File
@@ -0,0 +1,3 @@
*.tsbuildinfo
node_modules
lib
+8
View File
@@ -0,0 +1,8 @@
.github
*.tsbuildinfo
.versionrc.json
.vscode
CODEOWNERS
src
test
tsconfig.json
+1
View File
@@ -0,0 +1 @@
semi: false
+3
View File
@@ -0,0 +1,3 @@
{
"releaseCommitMessageFormat": "build(release): {{currentTag}}"
}
+3
View File
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}
+17
View File
@@ -0,0 +1,17 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "watch",
"type": "shell",
"command": "npm run watch",
"isBackground": true,
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
+1
View File
@@ -0,0 +1 @@
Lukas Obermann <lukas.obermann@icloud.com>
+1
View File
@@ -0,0 +1 @@
* @elyukai
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+1
View File
@@ -0,0 +1 @@
# Optolith Helpers
+3688
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@optolith/helpers",
"version": "0.1.0",
"description": "A set of JavaScript helper functions for multiple Optolith packages.",
"main": "lib/index.js",
"scripts": {
"build": "tsc -b",
"watch": "tsc -b -w",
"release": "commit-and-tag-version",
"test": "glob -c \"node --import tsx --test\" \"./test/**/*.ts\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/Optolith/helpers.git"
},
"author": "Lukas Obermann",
"license": "MPL-2.0",
"bugs": {
"url": "https://github.com/Optolith/helpers/issues"
},
"homepage": "https://github.com/Optolith/helpers#readme",
"devDependencies": {
"@types/node": "^22.7.4",
"commit-and-tag-version": "^12.4.4",
"glob": "^11.0.0",
"tsx": "^4.19.1",
"typescript": "^5.6.2"
},
"type": "module"
}
+226
View File
@@ -0,0 +1,226 @@
import { Equality } from "./compare.js"
import { isNotNullish } from "./nullable.js"
/**
* Filters out `null` and `undefined` values from the arguments and turns them
* into an array.
*/
export const arrayFromNonNullable = <T>(...args: T[]): NonNullable<T>[] =>
args.filter(isNotNullish)
/**
* Filters out `null` and `undefined` values from an array.
*/
export const filterNonNullable = <T>(array: T[]): NonNullable<T>[] =>
array.filter(isNotNullish)
/**
* Returns a range of numbers from `start` to `end` (inclusive).
* @param start The first number in the range.
* @param end The last number in the range.
* @throws `RangeError` if the upper bound is lower than the lower bound.
*/
export const range = (start: number, end: number): number[] => {
if (start > end) {
throw new RangeError(
"The upper bound must be greater than or equal to the lower bound."
)
}
return Array.from({ length: end - start + 1 }, (_, i) => i + start)
}
/**
* Returns a range of numbers between and including two numbers. The order of
* the arguments does not matter.
* @param start The first number in the range.
* @param end The last number in the range.
*/
export const rangeSafe = (start: number, end: number): number[] =>
start > end ? range(end, start) : range(start, end)
/**
* Returns the sum of all numbers in the given array.
*/
export const sum = (arr: number[]): number =>
arr.reduce((acc, value) => acc + value, 0)
/**
* Returns the sum of values returned by applying the given function to each
* element in the array.
*/
export const sumWith = <T>(arr: T[], fn: (value: T) => number): number =>
arr.reduce((acc, value) => acc + fn(value), 0)
/**
* Filters out duplicate values from an array. Objects are not supported, since
* they dont provide value equality semantics.
*/
export const unique = <
T extends number | boolean | string | symbol | null | undefined
>(
arr: T[]
): T[] => Array.from(new Set(arr))
/**
* Returns `true` if the two arrays are equal, `false` otherwise.
*/
export const arrayEqual = <
T extends number | boolean | string | symbol | null | undefined
>(
arr1: T[],
arr2: T[]
): boolean =>
arr1.length === arr2.length &&
arr1.every((value, index) => value === arr2[index])
/**
* Returns `undefined` if the array is empty, otherwise the non-empty array.
*/
export const ensureNonEmpty = <T>(arr: T[]): T[] | undefined =>
arr.length > 0 ? arr : undefined
/**
* Counts the number of elements in an array that satisfy the given predicate.
*/
export const count = <T>(
arr: T[],
predicate: (value: T, index: number) => boolean
): number =>
arr.reduce(
(acc, value, index) => (predicate(value, index) ? acc + 1 : acc),
0
)
/**
* Counts the number of elements the function returns the same value for and
* returns the count for all returned values as an object.
*/
export const countBy = <T, K extends string | number | symbol>(
arr: T[],
fn: (value: T, index: number) => K
): { [key in K]: number } =>
arr.reduce((acc, value, index) => {
const key = fn(value, index)
acc[key] = (acc[key] ?? 0) + 1
return acc
}, {} as { [key in K]: number })
/**
* Counts the number of elements the function returns the same values for and
* returns the count for all returned values as an object.
*/
export const countByMany = <T, K extends string | number | symbol>(
arr: T[],
fn: (value: T, index: number) => K[]
): { [key in K]: number } =>
arr.reduce((acc, value, index) => {
const keys = fn(value, index)
unique(keys).forEach((key) => {
acc[key] = (acc[key] ?? 0) + 1
})
return acc
}, {} as { [key in K]: number })
/**
* Partitions an array into two arrays based on a predicate.
* @param arr The array to split.
* @param predicate The function to apply to each element in the array.
* @returns An array with two elements, the first one containing all elements
* that satisfy the predicate, the second one containing all elements that do
* not satisfy the predicate.
*/
export function partition<T, T1 extends T>(
arr: T[],
predicate: (value: T) => value is T1
): [pos: T1[], neg: T[]]
export function partition<T>(
arr: T[],
predicate: (value: T) => boolean
): [pos: T[], neg: T[]]
/**
* Partitions an array into two arrays based on a predicate.
* @param arr The array to split.
* @param predicate The function to apply to each element in the array.
* @returns An array with two elements, the first one containing all elements
* that satisfy the predicate, the second one containing all elements that do
* not satisfy the predicate.
*/
export function partition<T>(
arr: T[],
predicate: (value: T) => boolean
): [pos: T[], neg: T[]] {
return arr.reduce<[T[], T[]]>(
(acc, value) => {
acc[predicate(value) ? 0 : 1].push(value)
return acc
},
[[], []]
)
}
/**
* Reduces an array, but stops as soon as the predicate returns `true` for an
* accumulated value (including the initial value) and returns the last
* accumulated value.
* @param arr The array to reduce.
* @param fn The function to apply to each element in the array.
* @param pred The predicate to apply to the initial value and to every result
* of a call to `fn`, where if it returns `true`, the reduction stops.
* @param initial The initial value.
*/
export const reduceWhile = <T, U>(
arr: T[],
fn: (acc: U, value: T, index: number) => U,
pred: (acc: U) => boolean,
initial: U
): U => {
let acc = initial
let index = 0
while (index < arr.length && !pred(acc)) {
acc = fn(acc, arr[index]!, index)
index++
}
return acc
}
/**
* Returns `true` if the array contains at least `minCount` elements that
* satisfy the given predicate, `false` otherwise.
*/
export const someCount = <T>(
arr: T[],
predicate: (value: T) => boolean,
minCount: number
): boolean =>
reduceWhile(
arr,
(acc, value) => (predicate(value) ? acc + 1 : acc),
(acc) => acc >= minCount,
0
) >= minCount
/**
* Returns a new array with all elements from the original array except for the
* given index.
*/
export const removeIndex = <T>(arr: T[], index: number): T[] => [
...arr.slice(0, index),
...arr.slice(index + 1),
]
/**
* Returns a new array, where adjacent elements that are considered equal by the
* given equality function are grouped together. Calling the `flat` method on
* the result will return the original array.
*/
export const groupBy = <T>(arr: T[], equal: Equality<T>): T[][] =>
arr.reduce<T[][]>((acc, value) => {
const lastGroup = acc[acc.length - 1]
if (lastGroup?.[0] !== undefined && equal(lastGroup[0], value)) {
lastGroup.push(value)
} else {
acc.push([value])
}
return acc
}, [])
+18
View File
@@ -0,0 +1,18 @@
/**
* Returns a string of class names from the given arguments. Filters out
* nullable values and keys with falsey values.
*/
export const classList = (
...cls: (string | null | undefined | Record<string, boolean | undefined>)[]
): string =>
cls
.flatMap(cl => {
if (cl === null || cl === undefined) {
return []
} else if (typeof cl === "string") {
return [cl]
} else {
return Object.entries(cl).flatMap(([k, v]) => (v === true ? [k] : []))
}
})
.join(" ")
+115
View File
@@ -0,0 +1,115 @@
import { isNullish } from "./nullable.js"
/**
* The type of a compare function that can be used to sort values.
* @returns A negative number if `a` should be sorted before `b`, a positive
* number if `a` should be sorted after `b`, or zero if `a` and `b` are equal.
*/
export type Compare<T> = (a: T, b: T) => number
/**
* Build a compare function for values that are nested inside other values. The
* nested value is getting extracted by the provided accessor function and then
* compared using the provided compare function. An optional `reverse` parameter
* can be used to reverse the sort order.
*/
export const compareAt =
<T, U>(
accessor: (value: T) => U,
compare: (a: U, b: U) => number,
reverse = false
): Compare<T> =>
(a, b) => {
const result = compare(accessor(a), accessor(b))
return reverse ? -result : result
}
/**
* Build a compare function that nests multiple compare functions. The functions
* are applied in order, so the first function is the primary sort key, the
* second function is the secondary sort key, and so on.
*/
export const reduceCompare =
<T>(...compares: Compare<T>[]): Compare<T> =>
(a, b) => {
for (const compare of compares) {
const result = compare(a, b)
if (result !== 0) {
return result
}
}
return 0
}
/**
* Compare function for numbers that sorts them in ascending order.
*/
export const numAsc: Compare<number> = (a, b) => a - b
/**
* Higher-order compare function that extends a compare function to also handle
* `null` and `undefined` values. Nullish values are always sorted first.
*/
export const compareNullish =
<T extends NonNullable<unknown>>(compare: Compare<T>) =>
(a: T | null | undefined, b: T | null | undefined): number => {
if (isNullish(a) && isNullish(b)) {
return 0
}
if (isNullish(a)) {
return -1
}
if (isNullish(b)) {
return 1
}
return compare(a, b)
}
/**
* A function that compares two values for equality.
*/
export type Equality<T> = (a: T, b: T) => boolean
/**
* Build an equality function for values that are nested inside other values.
* The nested value is getting extracted by the provided accessor function and
* then compared using the provided equality function.
*/
export const equalityAt =
<T, U>(accessor: (value: T) => U, equality: Equality<U>): Equality<T> =>
(a, b) =>
equality(accessor(a), accessor(b))
/**
* Checks two values for value equality. This is a deep equality check that
* works for all types, including objects and arrays. For objects, it only
* compares all enumerable keys, no other properties or the prototype chain.
*/
export const deepEqual = <T>(a: T, b: T): boolean => {
if (a === b) {
return true
}
if (
typeof a === "object" &&
typeof b === "object" &&
a !== null &&
b !== null
) {
const keys = Object.keys(a)
if (keys.length !== Object.keys(b).length) {
return false
}
return keys.every(
(key) =>
key in b &&
deepEqual(a[key as keyof typeof a], b[key as keyof typeof b])
)
}
return false
}
+6
View File
@@ -0,0 +1,6 @@
import { Compare } from "./compare.js"
/**
* A comparator function for {@link Date} objects in ascending order.
*/
export const compareDate: Compare<Date> = (a, b) => a.getTime() - b.getTime()
+39
View File
@@ -0,0 +1,39 @@
/**
* Returns a function that always returns the given value.
* @param value The value to return from the new function.
* @returns A new function that always returns the given value.
*/
export const constant =
<T>(value: T) =>
() =>
value
/**
* Returns a function that applies the given predicates to the given value and
* returns `true` if all predicates return `true`.
*/
export const andEvery =
<T>(...predicates: ((value: T) => boolean)[]) =>
(value: T): boolean =>
predicates.every(predicate => predicate(value))
export function orSome<T, U extends T, V extends T>(
f: (value: T) => value is U,
g: (value: T) => value is V,
): (value: T) => value is U | V
export function orSome<T>(...fns: ((value: T) => boolean)[]): (value: T) => boolean
/**
* Returns a function that combines predicate functions disjunctionally.
*/
export function orSome<T>(...predicates: ((value: T) => boolean)[]): (value: T) => boolean {
return value => predicates.some(predicate => predicate(value))
}
/**
* Returns a function that applies the given predicate to the given value and
* returns the negated result.
*/
export const not =
<T>(predicate: (value: T) => boolean) =>
(value: T): boolean =>
!predicate(value)
+38
View File
@@ -0,0 +1,38 @@
import { assertExhaustive } from "./typeSafety.js"
/**
* A lazy value that is only evaluated when it is needed.
*/
export class Lazy<T> {
private state:
| { kind: "unevaluated"; f: () => T }
| { kind: "evaluated"; value: T }
private constructor(f: () => T) {
this.state = { kind: "unevaluated", f }
}
/**
* Creates a new lazy value.
*/
public static of<T>(f: () => T): Lazy<T> {
return new Lazy(f)
}
/**
* The value of the lazy value. If the value has not been evaluated
* yet, it will be evaluated and cached.
*/
get value(): T {
switch (this.state.kind) {
case "unevaluated": {
this.state = { kind: "evaluated", value: this.state.f() }
return this.state.value
}
case "evaluated":
return this.state.value
default:
return assertExhaustive(this.state)
}
}
}
+66
View File
@@ -0,0 +1,66 @@
import { isInteger, isNaturalNumber } from "./regex.js"
/**
* The minus sign.
*/
export const minus = ""
/**
* The plus/minus sign.
*/
export const plusMinus = "\xB1"
/**
* Forces signing on the given number, returning `undefined` on zero.
*/
export const signIgnoreZero = (x: number): string | undefined =>
x > 0 ? `+${x}` : x < 0 ? `${minus}\u2060${Math.abs(x)}` : undefined
/**
* Forces signing on the given number.
*/
export const sign = (x: number): string =>
x > 0 ? `+${x}` : x < 0 ? `${minus}\u2060${Math.abs(x)}` : "0"
/**
* Returns the sign of the given number. Returns `undefined` if the number is
* zero.
*/
export const signStr = (x: number): string | undefined =>
x > 0 ? "+" : x < 0 ? minus : undefined
/**
* Converts a string to an integer. If the string is not a valid integer, it
* returns `undefined`.
*/
export const parseInt = (str: string): number | undefined =>
str.length > 0 && isInteger(str) ? Number.parseInt(str, 10) : undefined
/**
* Converts a string to a natural number. If the string is not a valid natural
* number, it returns `undefined`.
*/
export const parseNat = (str: string): number | undefined =>
str.length > 0 && isNaturalNumber(str) ? Number.parseInt(str, 10) : undefined
/**
* Returns a random integer between `0` and `max` (inclusive).
*/
export const randomInt = (max: number): number =>
Math.floor(Math.random() * (max + 1))
/**
* Returns a random integer between `min` and `max` (inclusive).
*/
export const randomIntRange = (min: number, max: number): number =>
Math.floor(Math.random() * (max + 1 - min)) + min
/**
* Returns if the given number is even.
*/
export const even = (x: number): boolean => x % 2 === 0
/**
* Returns if the given number is odd.
*/
export const odd = (x: number): boolean => x % 2 !== 0
+80
View File
@@ -0,0 +1,80 @@
/**
* A maybe can contain a value or nothing.
*/
export type Maybe<T> = Just<T> | Nothing
/**
* A maybe that contains a value.
*/
export type Just<T> = { readonly tag: "Just"; readonly value: T }
/**
* A maybe that contains nothing.
*/
export type Nothing = { readonly tag: "Nothing" }
/**
* Creates a maybe that contains a value.
*/
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const Just = <T>(value: T): Maybe<T> => ({ tag: "Just", value })
/**
* Checks if a maybe contains a value.
*/
export const isJust = <T>(result: Maybe<T>): result is Just<T> => result.tag === "Just"
/**
* Creates a maybe that contains nothing.
*/
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const Nothing: Maybe<never> = { tag: "Nothing" }
/**
* Checks if a maybe contains nothing.
*/
export const isNothing = <T>(result: Maybe<T>): result is Nothing => result.tag === "Nothing"
/**
* Creates a maybe from a nullable value.
*/
export const fromNullable = <T>(value: T): Maybe<NonNullable<T>> =>
value === null || value === undefined ? Nothing : Just(value)
/**
* Reduces a maybe to a value of a common type.
*/
export const reduce = <T, R>(maybe: Maybe<T>, def: R, f: (value: T) => R): R =>
isJust(maybe) ? f(maybe.value) : def
/**
* Maps the value of a maybe to a new value.
*/
export const map = <T, U>(maybe: Maybe<T>, f: (value: T) => U): Maybe<U> =>
isJust(maybe) ? Just(f(maybe.value)) : Nothing
/**
* Combines two maybes into one maybe. If both maybes contain a value, the
* values are combined using the provided function. If at least one maybe
* contains nothing, nothing is returned.
*/
export const combine = <T1, T2, TR>(
maybe1: Maybe<T1>,
maybe2: Maybe<T2>,
f: (value1: T1, value2: T2) => TR,
): Maybe<TR> => (isJust(maybe1) && isJust(maybe2) ? Just(f(maybe1.value, maybe2.value)) : Nothing)
/**
* A namespace for maybe functions.
*/
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const Maybe = Object.freeze({
Just,
isJust,
Nothing,
isNothing,
fromNullable,
reduce,
map,
combine,
})
+65
View File
@@ -0,0 +1,65 @@
/**
* Extracts `null` and `undefined` from a type.
*/
export type Nullish<T = null | undefined> = T extends null | undefined ? T : never
/**
* Checks if a value is `null` or `undefined`.
*/
export const isNullish = <T>(value: T): value is Exclude<T, NonNullable<T>> =>
value === null || value === undefined
/**
* Checks if a value is not `null` or `undefined`.
*/
export const isNotNullish = <T>(value: T): value is NonNullable<T> => !isNullish(value)
/**
* Maps a value to another value if it is not `null` or `undefined`.
*/
export const mapNullable = <T, U>(value: T, map: (value: NonNullable<T>) => U): U | Nullish<T> =>
isNotNullish(value) ? map(value) : (value as Nullish<T>)
/**
* Maps a value to another value if it is not `null` or `undefined`, otherwise
* returns a default value.
*/
export const mapNullableDefault = <T, U>(
value: T,
map: (value: NonNullable<T>) => U,
defaultValue: U,
): U => (isNotNullish(value) ? map(value) : defaultValue)
/**
* Returns an array, containing the value if it is not `null` or `undefined`.
*
* This can be useful in combination with the spread operator or
* `Array.prototype.flatMap`.
* @example
* nullableToArray(2) // [2]
* nullableToArray(undefined) // []
*
* [...nullableToArray(2)] // [2]
* [1, ...nullableToArray(2)] // [1, 2]
* [1, ...nullableToArray(undefined)] // [1]
*/
export const nullableToArray = <T>(value: T): NonNullable<T>[] =>
isNotNullish(value) ? [value] : []
/**
* Returns the value if it matches the given predicate, otherwise `undefined`.
*/
export function ensure<T, T1 extends T>(
value: T,
predicate: (value: T) => value is T1,
): T1 | undefined
/**
* Returns the value if it matches the given predicate, otherwise `undefined`.
*/
export function ensure<T>(value: T, predicate: (value: T) => boolean): T | undefined
/**
* Returns the value if it matches the given predicate, otherwise `undefined`.
*/
export function ensure<T>(value: T, predicate: (value: T) => boolean): T | undefined {
return predicate(value) ? value : undefined
}
+21
View File
@@ -0,0 +1,21 @@
/**
* Maps all own properties of an object to a new object. Returning `undefined`
* from the mapping function will omit the property from the result.
*/
export const mapObject = <T extends object, U>(
object: T,
map: (value: T[keyof T], key: keyof T) => U | undefined,
): { [key in keyof T]: Exclude<U, undefined> } => {
const result: { [key in keyof T]: Exclude<U, undefined> } = {} as never
for (const key in object) {
if (Object.hasOwn(object, key)) {
const newValue = map(object[key], key)
if (newValue !== undefined) {
result[key] = newValue as Exclude<U, undefined>
}
}
}
return result
}
+46
View File
@@ -0,0 +1,46 @@
/**
* A pair that specifies the lower (including) and upper (including) bounds of a
* contiguous subrange of integer values.
*/
export type RangeBounds = [lowerIncl: number, upperIncl: number]
/**
* The list of values in the subrange defined by a bounding pair.
* @throws {RangeError} If the upper bound is lower than the lower bound.
*/
export const range = (bounds: RangeBounds): number[] => {
const [start, end] = bounds
if (start > end) {
throw new RangeError("The upper bound must be greater than or equal to the lower bound.")
}
return Array.from({ length: end - start + 1 }, (_, i) => i + start)
}
/**
* Checks whether the passed `value` is within the range specified by the passed
* `bounds`.
*/
export const isInRange = (bounds: RangeBounds, value: number): boolean =>
value >= bounds[0] && value <= bounds[1]
/**
* Returns the index of a value in a range.
* @throws {RangeError} If the passed `value` is not within the range specified.
*/
export const indexInRange = (bounds: RangeBounds, value: number) => {
if (!isInRange(bounds, value)) {
throw new RangeError(
`indexInRange: index for ${value} is out of range (${bounds[0]}...${bounds[1]})`,
)
}
return value - bounds[0]
}
/**
* Returns the size of the range defined by the passed bounds.
*/
export const rangeSize = (bounds: RangeBounds): number =>
bounds[0] <= bounds[1] ? bounds[1] - bounds[0] + 1 : 0
+39
View File
@@ -0,0 +1,39 @@
/**
* Checks if the provided string is a string representation of a natural number.
* @param test The string to test.
*/
export const isNaturalNumber = (test: string) => /^(?:0|[1-9][0-9]*)$/u.test(test)
/**
* Checks if the provided string is a string representation of an integer.
* @param test The string to test.
*/
export const isInteger = (test: string) => /^(?:0|-?[1-9][0-9]*)$/u.test(test)
/**
* Checks if the provided string is a string representation of a floating-point
* number. Both `.` and `,` are accepted as decimal separators.
* @param test The string to test.
*/
export const isFloat = (test: string) => /^(?:(?:0|-?[1-9][0-9]*)(?:[.,][0-9]+)?)$/u.test(test)
/**
* Checks if the provided string either is an empty string or passes the given
* test function.
* @param check The test function to apply if the string is not empty.
* @param test The string to test.
*/
export const isEmptyOr = (check: (test: string) => boolean, test: string) =>
test === "" || check(test)
/**
* Checks if the provided string is a valid URL.
* @param test The string to test.
*/
export const isUrl = (test: string) => {
try {
return typeof new URL(test) === "object"
} catch {
return false
}
}
+49
View File
@@ -0,0 +1,49 @@
import { minus } from "./math.js"
const signPairs: [one: string, five: string][] = [
["I", "V"],
["X", "L"],
["C", "D"],
["M", "ↁ"],
]
const romanizeNatural = (num: number): string =>
num
.toString(10)
.split("")
.reverse()
.map((digit, index) => {
const pair = signPairs[index]
if (pair === undefined) {
return "?"
}
const value = parseInt(digit, 10)
const [one, five] = pair
if (value <= 3) {
return one.repeat(value)
} else if (value === 4) {
return one + five
} else if (value <= 8) {
return five + one.repeat(value - 5)
} else {
return one + (signPairs[index + 1]?.[0] ?? "?")
}
})
.reverse()
.join("")
/**
* Converts a number to a roman numeral.
*/
export const romanize = (num: number): string => {
if (num === 0) {
return "0"
} else if (num < 0) {
return minus + romanizeNatural(-num)
} else {
return romanizeNatural(num)
}
}
+5
View File
@@ -0,0 +1,5 @@
/**
* Checks if a value is a non-empty string.
*/
export const isNonEmptyString = (value: string | null | undefined): value is string =>
typeof value === "string" && value.length > 0
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"composite": true,
"declaration": true,
"forceConsistentCasingInFileNames": true,
"lib": ["esnext"],
"module": "NodeNext",
"noEmitHelpers": true,
"noErrorTruncation": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"outDir": "../lib",
"sourceMap": true,
"strict": true,
"target": "ESNext",
"useUnknownInCatchVariables": true,
}
}
+16
View File
@@ -0,0 +1,16 @@
/**
* This function is used to make sure that the `switch` is exhaustive. Place it
* in the `default` case of the `switch`.
* @param _x - The value that is used in the `switch`.
* @example
* const aorb = (x: "a" | "b") => {
* switch (x) {
* case "a": return 1
* case "b": return 2
* default: return assertExhaustive(x)
* }
* }
*/
export function assertExhaustive(_x: never): never {
throw new Error("The switch is not exhaustive.")
}
+266
View File
@@ -0,0 +1,266 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
arrayFromNonNullable,
count,
countBy,
countByMany,
ensureNonEmpty,
filterNonNullable,
groupBy,
partition,
range,
rangeSafe,
reduceWhile,
someCount,
sum,
sumWith,
unique,
} from "../src/array.js"
describe("arrayFromNonNullable", () => {
it("returns an array with null and undefined removed", () => {
assert.deepEqual(
arrayFromNonNullable(1, 2, null, 3, undefined, 4, 5),
[1, 2, 3, 4, 5]
)
})
})
describe("filterNonNullable", () => {
it("returns an array with null and undefined removed", () => {
assert.deepEqual(
filterNonNullable([1, 2, null, 3, undefined, 4, 5]),
[1, 2, 3, 4, 5]
)
})
})
describe("range", () => {
it("returns an array with all values between and including its bounds", () => {
assert.deepEqual(range(3, 3), [3])
assert.deepEqual(range(3, 8), [3, 4, 5, 6, 7, 8])
})
it("throws an errors if the upper bound is lower than the lower bound", () => {
assert.throws(() => range(3, 2))
})
})
describe("rangeSafe", () => {
it("returns an array with all values between and including its bounds", () => {
assert.deepEqual(rangeSafe(3, 3), [3])
assert.deepEqual(rangeSafe(3, 8), [3, 4, 5, 6, 7, 8])
assert.deepEqual(rangeSafe(8, 3), [3, 4, 5, 6, 7, 8])
})
})
describe("sum", () => {
it("returns 0 if the array is empty", () => {
assert.equal(sum([]), 0)
})
it("returns the sum of all numbers in the array", () => {
assert.equal(sum([1]), 1)
assert.equal(sum([1, 2]), 3)
assert.equal(sum([1, 2, 3]), 6)
assert.equal(sum([1, 2, 3, 4]), 10)
})
})
describe("sumWith", () => {
it("returns 0 if the array is empty", () => {
assert.equal(
sumWith([], (x) => x * 2),
0
)
})
it("returns the sum of all mapped numbers in the array", () => {
assert.equal(
sumWith([1], (x) => x * 2),
2
)
assert.equal(
sumWith([1, 2], (x) => x * 2),
6
)
assert.equal(
sumWith([1, 2, 3], (x) => x * 2),
12
)
assert.equal(
sumWith([1, 2, 3, 4], (x) => x * 2),
20
)
})
})
describe("unique", () => {
it("filters out duplicate values from an array", () => {
assert.deepEqual(unique([]), [])
assert.deepEqual(unique([1, 2, 3]), [1, 2, 3])
assert.deepEqual(unique([1, 2, 1, 3]), [1, 2, 3])
})
})
describe("ensureNonEmpty", () => {
it("returns undefined if the array is empty", () => {
assert.deepEqual(ensureNonEmpty([]), undefined)
})
it("returns the non-empty array as-is", () => {
assert.deepEqual(ensureNonEmpty([1, 2]), [1, 2])
})
})
describe("count", () => {
it("returns how many elements satify the given predicate", () => {
assert.equal(
count([], (x) => x > 3),
0
)
assert.equal(
count([0, 2, 3], (x) => x >= 3),
1
)
assert.equal(
count([0, 2, 4, 6, 8], (x) => x > 3),
3
)
})
})
describe("countBy", () => {
it("returns an empty object of the array is empty", () => {
assert.deepEqual(
countBy([], (x) => x % 2),
{}
)
})
it("returns for how many elements the function returns the same value", () => {
assert.deepEqual(
countBy([0, 2, 3], (x) => x % 2),
{ 0: 2, 1: 1 }
)
assert.deepEqual(
countBy([0, 2, 4, 6, 8], (x) => x % 2),
{ 0: 5 }
)
})
})
describe("countByMany", () => {
it("returns an empty object of the array is empty", () => {
assert.deepEqual(
countByMany([], (x) => [x, Math.round(x / 2), x % 2]),
{}
)
})
it("returns for how many elements the function returns the same value", () => {
assert.deepEqual(
countByMany([0, 2, 3], (x) => [x, Math.round(x / 2), x % 2]),
{ 0: 2, 1: 2, 2: 2, 3: 1 }
)
assert.deepEqual(
countByMany([0, 2, 4, 6, 8], (x) => [x, Math.round(x / 2), x % 2]),
{ 0: 5, 1: 1, 2: 2, 3: 1, 4: 2, 6: 1, 8: 1 }
)
})
})
describe("partition", () => {
it("splits all array elements into two separate arrays based on a predicate", () => {
assert.deepEqual(
partition([], (x) => x >= 3),
[[], []]
)
assert.deepEqual(
partition([0, 2, 3], (x) => x >= 3),
[[3], [0, 2]]
)
assert.deepEqual(
partition([0, 2, 4, 6, 8], (x) => x >= 3),
[
[4, 6, 8],
[0, 2],
]
)
})
it("keeps the original order of elements", () => {
assert.deepEqual(
partition([4, 8, 2, 7, 5, 6, 1, 3], (x) => x >= 3),
[
[4, 8, 7, 5, 6, 3],
[2, 1],
]
)
})
})
describe("reduceWhile", () => {
it("should return the initial value for an empty array", () => {
const result = reduceWhile(
[],
(acc, value) => acc + value,
() => false,
10
)
assert.equal(result, 10)
})
it("should correctly reduce the array", () => {
const result = reduceWhile(
[1, 2, 3, 4, 5],
(acc, value) => acc + value,
() => false,
0
)
assert.equal(result, 15)
})
it("should break early and return the correct value", () => {
const result = reduceWhile(
[1, 2, 3, 4, 5],
(acc, value) => acc + value,
(acc) => acc > 3,
0
)
assert.equal(result, 6)
})
})
describe("someCount", () => {
it("should return true if the array has the required minimum elements that satisfy the predicate", () => {
const result = someCount([1, 2, 3, 4, 5], (value) => value > 2, 3)
assert.equal(result, true)
})
it("should return false if the array does not have the required minimum elements that satisfy the predicate", () => {
const result = someCount([1, 2, 3, 4, 5], (value) => value > 5, 3)
assert.equal(result, false)
})
it("should return true for an array that has exactly the required number of elements satisfying the predicate", () => {
const result = someCount([1, 2, 3, 4, 5], (value) => value > 3, 2)
assert.equal(result, true)
})
it("should return false for an empty array", () => {
const result = someCount([], (value) => value === 0, 2)
assert.equal(result, false)
})
})
describe("groupBy", () => {
it("should return an empty array for an empty input", () => {
const result = groupBy([], (a, b) => a === b)
assert.deepEqual(result, [])
})
it("should group adjacent elements that are equal", () => {
const result = groupBy([1, 1, 2, 2, 2, 3, 4, 4, 4, 4], (a, b) => a === b)
assert.deepEqual(result, [[1, 1], [2, 2, 2], [3], [4, 4, 4, 4]])
})
})
+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { classList } from "../src/classList.js"
describe("classList", () => {
it("returns a string of class names from the given arguments", () => {
assert.equal(
classList("foo", "bar", undefined, null, {
baz: true,
no: false,
alsoNo: undefined,
}),
"foo bar baz"
)
})
})
+82
View File
@@ -0,0 +1,82 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { compareAt, deepEqual, numAsc, reduceCompare } from "../src/compare.js"
describe("compareAt", () => {
it("builds a compare function for a nested value", () => {
const compare1 = compareAt(
(x: { first: number; second: number }) => x.first,
numAsc
)
assert.equal(compare1({ first: 3, second: 6 }, { first: 2, second: 2 }), 1)
const compare2 = compareAt(
(x: { first: number; second: number }) => x.second,
numAsc,
true
)
assert.equal(compare2({ first: 3, second: 6 }, { first: 2, second: 2 }), -4)
})
})
describe("reduceCompare", () => {
it("chains multiple comparison functions", () => {
assert.deepEqual(
[
{ first: 2, second: 6 },
{ first: 2, second: 2 },
{ first: 1, second: 2 },
{ first: 3, second: 1 },
{ first: 1, second: 6 },
{ first: 2, second: 3 },
].sort(
reduceCompare(
compareAt((x) => x.first, numAsc),
compareAt((x) => x.second, numAsc, true)
)
),
[
{ first: 1, second: 6 },
{ first: 1, second: 2 },
{ first: 2, second: 6 },
{ first: 2, second: 3 },
{ first: 2, second: 2 },
{ first: 3, second: 1 },
]
)
})
})
describe(deepEqual.name, () => {
it("returns true if two objects are equal", () => {
const object1 = { a: 1, b: { c: 2, d: [3, 4] } }
const object2 = { a: 1, b: { c: 2, d: [3, 4] } }
const object3 = { a: 1, b: { c: 2, d: [3, 4, 5] } }
const object4 = { a: 1, b: { c: 2 } }
const object5 = { a: 1, b: { c: 3 } }
const object6 = { a: 1, b: { c: 2, d: 4 } }
assert.equal(deepEqual(object1, object2), true)
assert.equal(deepEqual(object1, object3), false)
assert.equal(deepEqual(object4, object5), false)
assert.equal(deepEqual(object4, object6), false)
})
it("returns true if two objects are equal", () => {
const array1 = [1, 2, [3, 4, [5, 6]]]
const array2 = [1, 2, [3, 4, [5, 6]]]
const array3 = [1, 2, [3, 4, [5, 7]]]
assert.equal(deepEqual(array1, array2), true)
assert.equal(deepEqual(array1, array3), false)
})
it("returns true if two mixed objects and arrays are equal", () => {
const mixed1 = { a: 1, b: [2, 3, { c: 4, d: [5, 6] }] }
const mixed2 = { a: 1, b: [2, 3, { c: 4, d: [5, 6] }] }
const mixed3 = { a: 1, b: [2, 3, { c: 4, d: [5, 7] }] }
assert.equal(deepEqual(mixed1, mixed2), true)
assert.equal(deepEqual(mixed1, mixed3), false)
})
})
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { compareDate } from "../src/date.js"
describe("compareDate", () => {
it("returns a negative value if the first date is earlier than the second date", () => {
assert.equal(
compareDate(
new Date(2000, 0, 1, 12, 0, 0, 100),
new Date(2000, 0, 1, 12, 0, 0, 200)
),
-100
)
})
it("returns a positive value if the first date is later than the second date", () => {
assert.equal(
compareDate(
new Date(2000, 0, 1, 12, 0, 0, 300),
new Date(2000, 0, 1, 12, 0, 0, 200)
),
100
)
})
it("returns zero if the first date is equal to the second date", () => {
assert.equal(
compareDate(
new Date(2000, 0, 1, 12, 0, 0, 200),
new Date(2000, 0, 1, 12, 0, 0, 200)
),
0
)
})
})
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { andEvery, constant, not, orSome } from "../src/function.js"
describe("constant", () => {
it("returns a function that always returns the passed-in value as-is", () => {
const x = {}
assert.equal(constant(x)(), x)
})
})
describe("andEvery", () => {
it("returns a function that returns true if all predicates return true", () => {
const isEven = (x: number) => x % 2 === 0
const isPositive = (x: number) => x > 0
const isEvenAndPositive = andEvery(isEven, isPositive)
assert.equal(isEvenAndPositive(2), true)
assert.equal(isEvenAndPositive(3), false)
assert.equal(isEvenAndPositive(-2), false)
})
})
describe("orSome", () => {
it("returns a function that returns true if at least one predicate returns true", () => {
const isEven = (x: number) => x % 2 === 0
const isPositive = (x: number) => x > 0
const isEvenAndPositive = orSome(isEven, isPositive)
assert.equal(isEvenAndPositive(2), true)
assert.equal(isEvenAndPositive(3), true)
assert.equal(isEvenAndPositive(-3), false)
})
})
describe("not", () => {
it("returns a function that returns the negated result of the passed-in predicate", () => {
const isEven = (x: number) => x % 2 === 0
const isOdd = not(isEven)
assert.equal(isOdd(2), false)
assert.equal(isOdd(3), true)
})
})
+17
View File
@@ -0,0 +1,17 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { Lazy } from "../src/lazy.js"
describe("Lazy", () => {
it("evaluates its value only when it is needed", () => {
let evaluated = false
const lazy = Lazy.of(() => {
evaluated = true
return 42
})
assert.equal(evaluated, false)
assert.equal(lazy.value, 42)
assert.equal(evaluated, true)
})
})
+119
View File
@@ -0,0 +1,119 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
even,
odd,
parseInt,
parseNat,
sign,
signIgnoreZero,
signStr,
} from "../src/math.js"
describe("signIgnoreZero", () => {
it("adds a typographic minus sign to a negative number", () => {
assert.equal(signIgnoreZero(-1), "\u20601")
})
it("adds a plus sign to a positive number", () => {
assert.equal(signIgnoreZero(1), "+1")
})
it("returns undefined on zero", () => {
assert.equal(signIgnoreZero(0), undefined)
})
})
describe("sign", () => {
it("adds a typographic minus sign to a negative number", () => {
assert.equal(sign(-1), "\u20601")
})
it("adds a plus sign to a positive number", () => {
assert.equal(sign(1), "+1")
})
it("returns 0 on zero", () => {
assert.equal(sign(0), "0")
})
})
describe("signStr", () => {
it("returns a typographic minus sign on a negative number", () => {
assert.equal(signStr(-1), "")
})
it("returns a plus sign on a positive number", () => {
assert.equal(signStr(1), "+")
})
it("returns undefined on zero", () => {
assert.equal(signStr(0), undefined)
})
})
describe("parseInt", () => {
it("parses a string that completely represents an integer", () => {
assert.equal(parseInt("2"), 2)
assert.equal(parseInt("-2"), -2)
assert.equal(parseInt("10"), 10)
assert.equal(parseInt("-10"), -10)
})
it("returns undefined if the full string does not represent an integer", () => {
assert.equal(parseInt(""), undefined)
assert.equal(parseInt(" 2"), undefined)
assert.equal(parseInt("01"), undefined)
assert.equal(parseInt("1.4"), undefined)
assert.equal(parseInt("1,4"), undefined)
assert.equal(parseInt("1n"), undefined)
assert.equal(parseInt("NaN"), undefined)
})
})
describe("parseNat", () => {
it("parses a string that completely represents an integer", () => {
assert.equal(parseNat("2"), 2)
assert.equal(parseNat("10"), 10)
})
it("returns undefined if the full string does not represent an integer", () => {
assert.equal(parseNat("-2"), undefined)
assert.equal(parseNat("-10"), undefined)
assert.equal(parseNat(""), undefined)
assert.equal(parseNat(" 2"), undefined)
assert.equal(parseNat("01"), undefined)
assert.equal(parseNat("1.4"), undefined)
assert.equal(parseNat("1,4"), undefined)
assert.equal(parseNat("1n"), undefined)
assert.equal(parseNat("NaN"), undefined)
})
})
describe("even", () => {
it("returns if the given number is even", () => {
assert.equal(even(-4), true)
assert.equal(even(-3), false)
assert.equal(even(-2), true)
assert.equal(even(-1), false)
assert.equal(even(0), true)
assert.equal(even(1), false)
assert.equal(even(2), true)
assert.equal(even(3), false)
assert.equal(even(4), true)
})
})
describe("odd", () => {
it("returns if the given number is odd", () => {
assert.equal(odd(-4), false)
assert.equal(odd(-3), true)
assert.equal(odd(-2), false)
assert.equal(odd(-1), true)
assert.equal(odd(0), false)
assert.equal(odd(1), true)
assert.equal(odd(2), false)
assert.equal(odd(3), true)
assert.equal(odd(4), false)
})
})
+117
View File
@@ -0,0 +1,117 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
Just,
Nothing,
combine,
fromNullable,
isJust,
isNothing,
map,
reduce,
} from "../src/maybe.js"
describe(Just.name, () => {
it("creates a maybe that contains a value", () => {
const maybe = Just("hello")
assert.deepEqual(maybe, { tag: "Just", value: "hello" })
})
})
describe("Nothing", () => {
it("creates a maybe that contains nothing", () => {
const maybe = Nothing
assert.deepEqual(maybe, { tag: "Nothing" })
})
})
describe(isJust.name, () => {
it("returns true if the maybe contains a value", () => {
const maybe = Just("hello")
assert.equal(isJust(maybe), true)
})
it("returns false if the maybe contains nothing", () => {
const maybe = Nothing
assert.equal(isJust(maybe), false)
})
})
describe(isNothing.name, () => {
it("returns true if the maybe contains nothing", () => {
const maybe = Nothing
assert.equal(isNothing(maybe), true)
})
it("returns false if the maybe contains a value", () => {
const maybe = Just("hello")
assert.equal(isNothing(maybe), false)
})
})
describe(fromNullable.name, () => {
it("creates a maybe that contains a value if the input is not null or undefined", () => {
const maybe = fromNullable("hello")
assert.deepEqual(maybe, { tag: "Just", value: "hello" })
})
it("creates a maybe that contains nothing if the input is null", () => {
const maybe = fromNullable(null)
assert.deepEqual(maybe, { tag: "Nothing" })
})
it("creates a maybe that contains nothing if the input is undefined", () => {
const maybe = fromNullable(undefined)
assert.deepEqual(maybe, { tag: "Nothing" })
})
})
describe(reduce.name, () => {
it("returns the default value if the maybe contains nothing", () => {
const maybe = Nothing
const result = reduce<string, string>(maybe, "default", (value) =>
value.toUpperCase()
)
assert.equal(result, "default")
})
it("applies the function to the value if the maybe contains a value", () => {
const maybe = Just("hello")
const result = reduce(maybe, "default", (value) => value.toUpperCase())
assert.equal(result, "HELLO")
})
})
describe(map.name, () => {
it("returns a maybe that contains nothing if the input maybe contains nothing", () => {
const maybe = Nothing
const result = map<string, string>(maybe, (value) => value.toUpperCase())
assert.deepEqual(result, { tag: "Nothing" })
})
it("applies the function to the value if the input maybe contains a value", () => {
const maybe = Just("hello")
const result = map(maybe, (value) => value.toUpperCase())
assert.deepEqual(result, { tag: "Just", value: "HELLO" })
})
})
describe(combine.name, () => {
it("returns a maybe that contains nothing if either input maybe contains nothing", () => {
const maybe1 = Just("hello")
const maybe2 = Nothing
const result = combine(maybe1, maybe2, (value1, value2) => value1 + value2)
assert.deepEqual(result, { tag: "Nothing" })
})
it("applies the function to the values if both input maybes contain a value", () => {
const maybe1 = Just("hello")
const maybe2 = Just("world")
const result = combine(
maybe1,
maybe2,
(value1, value2) => `${value1} ${value2}`
)
assert.deepEqual(result, { tag: "Just", value: "hello world" })
})
})
+89
View File
@@ -0,0 +1,89 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
ensure,
isNotNullish,
isNullish,
mapNullable,
mapNullableDefault,
nullableToArray,
} from "../src/nullable.js"
describe("isNullish", () => {
it("returns if a value is nullish", () => {
assert.equal(isNullish(null), true)
assert.equal(isNullish(undefined), true)
assert.equal(isNullish(false), false)
assert.equal(isNullish(0), false)
assert.equal(isNullish(""), false)
})
})
describe("isNotNullish", () => {
it("returns if a value is not nullish", () => {
assert.equal(isNotNullish(null), false)
assert.equal(isNotNullish(undefined), false)
assert.equal(isNotNullish(false), true)
assert.equal(isNotNullish(0), true)
assert.equal(isNotNullish(""), true)
})
})
describe("mapNullable", () => {
it("maps a value if it is not nullish", () => {
assert.equal(
mapNullable(2, (x) => x * 2),
4
)
})
it("returns the original value if it is nullish", () => {
assert.equal(
mapNullable(undefined, (x) => x * 2),
undefined
)
})
})
describe("mapNullableDefault", () => {
it("maps a value if it is not nullish", () => {
assert.equal(
mapNullableDefault(2, (x) => x * 2, 0),
4
)
})
it("returns a default if the value is nullish", () => {
assert.equal(
mapNullableDefault(undefined, (x) => x * 2, 0),
0
)
})
})
describe("nullableToArray", () => {
it("wraps a non-nullish value into an array", () => {
assert.deepEqual(nullableToArray(2), [2])
})
it("returns an empty array if the value is null or undefined", () => {
assert.deepEqual(nullableToArray(undefined), [])
assert.deepEqual(nullableToArray(null), [])
})
})
describe("ensure", () => {
it("returns the value if it matches the predicate", () => {
assert.equal(
ensure(2, (x) => x === 2),
2
)
})
it("returns undefined if the value does not match the predicate", () => {
assert.equal(
ensure(2, (x) => x === 3),
undefined
)
})
})
+19
View File
@@ -0,0 +1,19 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { mapObject } from "../src/object.js"
describe("mapObject", () => {
it("maps all own properties of an object to a new object", () => {
const object = { a: 1, b: 2, c: 3 }
const result = mapObject(object, (value, key) => value + key)
assert.deepEqual(result, { a: "1a", b: "2b", c: "3c" })
})
it("omits properties for which the mapping function returns undefined", () => {
const object = { a: 1, b: 2, c: 3 }
const result = mapObject(object, (value, key) =>
key === "b" ? undefined : value + key
)
assert.deepEqual(result, { a: "1a", c: "3c" })
})
})
+44
View File
@@ -0,0 +1,44 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { indexInRange, isInRange, range, rangeSize } from "../src/range.js"
describe("range", () => {
it("returns an array with all values between and including its bounds", () => {
assert.deepEqual(range([3, 3]), [3])
assert.deepEqual(range([3, 8]), [3, 4, 5, 6, 7, 8])
})
it("throws an errors if the upper bound is lower than the lower bound", () => {
assert.throws(() => range([3, 2]))
})
})
describe("isInRange", () => {
it("returns if the value is within the specified range", () => {
assert.equal(isInRange([1, 5], 1), true)
assert.equal(isInRange([1, 5], 3), true)
assert.equal(isInRange([1, 5], -1), false)
})
})
describe("indexInRange", () => {
it("returns if the value is within the specified bounds", () => {
assert.equal(indexInRange([1, 5], 3), 2)
assert.equal(indexInRange([1, 5], 1), 0)
})
it("throws if the value is not within the specified bounds", () => {
assert.throws(() => indexInRange([1, 5], -1))
})
})
describe("rangeSize", () => {
it("returns a positive integer if the range is valid", () => {
assert.equal(rangeSize([1, 5]), 5)
assert.equal(rangeSize([1, 1]), 1)
})
it("returns 0 if the upper bound is smaller than the lower bound", () => {
assert.equal(rangeSize([1, -2]), 0)
})
})
+66
View File
@@ -0,0 +1,66 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
isEmptyOr,
isFloat,
isInteger,
isNaturalNumber,
isUrl,
} from "../src/regex.js"
describe("isNaturalNumber", () => {
it("returns if the passed string represents a natural number", () => {
assert.equal(isNaturalNumber("0"), true)
assert.equal(isNaturalNumber("1"), true)
assert.equal(isNaturalNumber("39570"), true)
assert.equal(isNaturalNumber("01"), false)
assert.equal(isNaturalNumber("1.4"), false)
assert.equal(isNaturalNumber("-1"), false)
assert.equal(isNaturalNumber("NaN"), false)
})
})
describe("isInteger", () => {
it("returns if the passed string represents an integer", () => {
assert.equal(isInteger("0"), true)
assert.equal(isInteger("1"), true)
assert.equal(isInteger("39570"), true)
assert.equal(isInteger("01"), false)
assert.equal(isInteger("1.4"), false)
assert.equal(isInteger("-1"), true)
assert.equal(isInteger("NaN"), false)
})
})
describe("isFloat", () => {
it("returns if the passed string represents a floating-point number", () => {
assert.equal(isFloat("0"), true)
assert.equal(isFloat("1"), true)
assert.equal(isFloat("39570"), true)
assert.equal(isFloat("01"), false)
assert.equal(isFloat("1.4"), true)
assert.equal(isFloat("1,4"), true)
assert.equal(isFloat("-1"), true)
assert.equal(isFloat("NaN"), false)
})
})
describe("isEmptyOr", () => {
it("returns if the passed string is empty or passed the given test function", () => {
assert.equal(isEmptyOr(isInteger, ""), true)
assert.equal(isEmptyOr(isInteger, "0"), true)
assert.equal(isEmptyOr(isInteger, "NaN"), false)
})
})
describe("isUrl", () => {
it("returns if the passed string is a valid url", () => {
assert.equal(isUrl(""), false)
assert.equal(isUrl("https://example.com"), true)
assert.equal(isUrl("https://example.com:8080"), true)
assert.equal(isUrl("https://example.com:8080/path"), true)
assert.equal(isUrl("https://example.com:8080/path?query=string"), true)
assert.equal(isUrl("https://example.com:8080/path?query=string#hash"), true)
assert.equal(isUrl("file:///etc/path?query=string#hash"), true)
})
})
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { romanize } from "../src/roman.js"
describe("romanize", () => {
it("returns 0 on 0", () => assert.equal(romanize(0), "0"))
it("returns I on 1", () => assert.equal(romanize(1), "I"))
it("returns V on 5", () => assert.equal(romanize(5), "V"))
it("returns IX on 9", () => assert.equal(romanize(9), "IX"))
it("returns XVIII on 18", () => assert.equal(romanize(18), "XVIII"))
it("returns IX on -9", () => assert.equal(romanize(-9), "IX"))
})
+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { isNonEmptyString } from "../src/string.js"
describe("isNonEmptyString", () => {
it("returns false on undefined", () =>
assert.equal(isNonEmptyString(undefined), false))
it("returns false on null", () => assert.equal(isNonEmptyString(null), false))
it("returns false on an empty string", () =>
assert.equal(isNonEmptyString(""), false))
it("returns true on a non-empty string", () => {
assert.equal(isNonEmptyString("a"), true)
assert.equal(isNonEmptyString("ab"), true)
assert.equal(isNonEmptyString("abc"), true)
})
})
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"composite": true,
"declaration": true,
"forceConsistentCasingInFileNames": true,
"lib": ["esnext"],
"module": "NodeNext",
"noEmit": true,
"noEmitHelpers": true,
"noErrorTruncation": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"outDir": "../libtest",
"sourceMap": true,
"strict": true,
"target": "ESNext",
"useUnknownInCatchVariables": true,
},
"references": [
{ "path": "../src" },
]
}
+14
View File
@@ -0,0 +1,14 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { assertExhaustive } from "../src/typeSafety.js"
describe("assertExhaustive", () => {
it("should throw an error with the message 'The switch is not exhaustive.'", () => {
assert.throws(
// @ts-expect-error The function should never receive a value.
() => assertExhaustive(""),
(err) =>
err instanceof Error && err.message === "The switch is not exhaustive."
)
})
})
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "src" },
{ "path": "test" },
],
}