Publish
This commit is contained in:
350
example/collections/array.ts
Normal file
350
example/collections/array.ts
Normal file
@@ -0,0 +1,350 @@
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/collections
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2025 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
|
||||
import { TypeCheck, TypeCompiler, ValueError } from '@sinclair/typebox/compiler'
|
||||
import { TSchema, Static, TypeBoxError } from '@sinclair/typebox'
|
||||
import { Value } from '@sinclair/typebox/value'
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// TypeArrayError
|
||||
// ----------------------------------------------------------------
|
||||
export class TypeArrayError extends TypeBoxError {
|
||||
constructor(message: string) {
|
||||
super(`${message}`)
|
||||
}
|
||||
}
|
||||
export class TypeArrayLengthError extends TypeBoxError {
|
||||
constructor() {
|
||||
super('arrayLength not a number')
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------------------------
|
||||
// TypeArray<T>
|
||||
// ----------------------------------------------------------------
|
||||
export class TypeArray<T extends TSchema> implements Iterable<Static<T>> {
|
||||
readonly #typeCheck: TypeCheck<T>
|
||||
readonly #values: Static<T>[]
|
||||
constructor(schema: T, arrayLength: number = 0) {
|
||||
if (typeof arrayLength !== 'number') throw new TypeArrayLengthError()
|
||||
this.#typeCheck = TypeCompiler.Compile(schema)
|
||||
this.#values = new Array(arrayLength)
|
||||
for (let i = 0; i < arrayLength; i++) {
|
||||
this.#values[i] = Value.Create(schema)
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Indexer
|
||||
// ---------------------------------------------------
|
||||
/** Sets the value at the given index */
|
||||
public set(index: number, item: Static<T>): void {
|
||||
this.#assertIndexInBounds(index)
|
||||
this.#assertItem(index, item)
|
||||
this.#values[index] = item
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Array<T>
|
||||
// ---------------------------------------------------
|
||||
/** Iterator for values in this array */
|
||||
public [Symbol.iterator](): IterableIterator<Static<T>> {
|
||||
return this.#values[Symbol.iterator]() as IterableIterator<T>
|
||||
}
|
||||
/** Gets the value at the given index */
|
||||
public at(index: number): Static<T> {
|
||||
this.#assertIndexInBounds(index)
|
||||
return this.#values[index] as T
|
||||
}
|
||||
/**
|
||||
* Gets the length of the array. This is a number one higher than the highest index in the array.
|
||||
*/
|
||||
public get length(): number {
|
||||
return this.#values.length
|
||||
}
|
||||
/**
|
||||
* Returns a string representation of an array.
|
||||
*/
|
||||
public toString(): string {
|
||||
return this.#values.toString()
|
||||
}
|
||||
/**
|
||||
* Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
|
||||
*/
|
||||
public toLocaleString(): string {
|
||||
return this.#values.toLocaleString()
|
||||
}
|
||||
/**
|
||||
* Removes the last element from an array and returns it.
|
||||
* If the array is empty, undefined is returned and the array is not modified.
|
||||
*/
|
||||
public pop(): Static<T> | undefined {
|
||||
return this.#values.pop()
|
||||
}
|
||||
/**
|
||||
* Appends new elements to the end of an array, and returns the new length of the array.
|
||||
* @param items New elements to add to the array.
|
||||
*/
|
||||
public push(...items: Static<T>[]): number {
|
||||
this.#assertItems(items)
|
||||
return this.#values.push(...items)
|
||||
}
|
||||
/**
|
||||
* Combines two or more arrays.
|
||||
* This method returns a new array without modifying any existing arrays.
|
||||
* @param items Additional arrays and/or items to add to the end of the array.
|
||||
*/
|
||||
public concat(...items: ConcatArray<Static<T>>[]): Static<T>[]
|
||||
/**
|
||||
* Combines two or more arrays.
|
||||
* This method returns a new array without modifying any existing arrays.
|
||||
* @param items Additional arrays and/or items to add to the end of the array.
|
||||
*/
|
||||
public concat(...items: (T | ConcatArray<Static<T>>)[]): Static<T>[] {
|
||||
this.#assertItems(items)
|
||||
return this.#values.concat(...items) as Static<T>[]
|
||||
}
|
||||
/**
|
||||
* Adds all the elements of an array into a string, separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
public join(separator?: string): string {
|
||||
return this.#values.join(separator)
|
||||
}
|
||||
/**
|
||||
* Reverses the elements in an array in place.
|
||||
* This method mutates the array and returns a reference to the same array.
|
||||
*/
|
||||
public reverse(): Static<T>[] {
|
||||
return this.#values.reverse() as Static<T>[]
|
||||
}
|
||||
/**
|
||||
* Removes the first element from an array and returns it.
|
||||
* If the array is empty, undefined is returned and the array is not modified.
|
||||
*/
|
||||
public shift(): Static<T> | undefined {
|
||||
return this.#values.shift() as Static<T> | undefined
|
||||
}
|
||||
/**
|
||||
* Returns a copy of a section of an array.
|
||||
* For both start and end, a negative index can be used to indicate an offset from the end of the array.
|
||||
* For example, -2 refers to the second to last element of the array.
|
||||
* @param start The beginning index of the specified portion of the array.
|
||||
* If start is undefined, then the slice begins at index 0.
|
||||
* @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.
|
||||
* If end is undefined, then the slice extends to the end of the array.
|
||||
*/
|
||||
public slice(start?: number, end?: number): Static<T>[] {
|
||||
return this.#values.slice(start, end) as Static<T>[]
|
||||
}
|
||||
/**
|
||||
* Sorts an array in place.
|
||||
* This method mutates the array and returns a reference to the same array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
*/
|
||||
public sort(compareFn?: (a: Static<T>, b: Static<T>) => number): this {
|
||||
this.#values.sort(compareFn as any)
|
||||
return this
|
||||
}
|
||||
/**
|
||||
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @returns An array containing the elements that were deleted.
|
||||
*/
|
||||
public splice(start: number, deleteCount?: number): Static<T>[]
|
||||
/**
|
||||
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @param items Elements to insert into the array in place of the deleted elements.
|
||||
* @returns An array containing the elements that were deleted.
|
||||
*/
|
||||
public splice(start: number, deleteCount: number, ...items: Static<T>[]): Static<T>[] {
|
||||
this.#assertItems(items)
|
||||
return this.#values.splice(start, deleteCount, items) as Static<T>[]
|
||||
}
|
||||
/**
|
||||
* Inserts new elements at the start of an array, and returns the new length of the array.
|
||||
* @param items Elements to insert at the start of the array.
|
||||
*/
|
||||
public unshift(...items: Static<T>[]): number {
|
||||
this.#assertItems(items)
|
||||
return this.#values.unshift(items)
|
||||
}
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array, or -1 if it is not present.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
|
||||
*/
|
||||
public indexOf(searchElement: Static<T>, fromIndex?: number): number {
|
||||
return this.#values.indexOf(searchElement, fromIndex)
|
||||
}
|
||||
/**
|
||||
* Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.
|
||||
*/
|
||||
public lastIndexOf(searchElement: Static<T>, fromIndex?: number): number {
|
||||
return this.#values.lastIndexOf(searchElement, fromIndex)
|
||||
}
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param predicate A function that accepts up to three arguments. The every method calls
|
||||
* the predicate function for each element in the array until the predicate returns a value
|
||||
* which is coercible to the Boolean value false, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public every<S extends T>(predicate: (value: Static<T>, index: number, array: Static<T>[]) => value is Static<S>, thisArg?: any): this is Static<S>[]
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param predicate A function that accepts up to three arguments. The every method calls
|
||||
* the predicate function for each element in the array until the predicate returns a value
|
||||
* which is coercible to the Boolean value false, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public every(predicate: (value: Static<T>, index: number, array: Static<T>[]) => unknown, thisArg?: any): boolean {
|
||||
return this.#values.every(predicate as any, thisArg)
|
||||
}
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param predicate A function that accepts up to three arguments. The some method calls
|
||||
* the predicate function for each element in the array until the predicate returns a value
|
||||
* which is coercible to the Boolean value true, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public some(predicate: (value: Static<T>, index: number, array: T[]) => unknown, thisArg?: any): boolean {
|
||||
return this.#values.some(predicate as any, thisArg)
|
||||
}
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public forEach(callbackfn: (value: Static<T>, index: number, array: Static<T>[]) => void, thisArg?: any): void {
|
||||
return this.#values.forEach(callbackfn as any, thisArg)
|
||||
}
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public map<U>(callbackfn: (value: Static<T>, index: number, array: Static<T>[]) => U, thisArg?: any): U[] {
|
||||
return this.#values.map(callbackfn as any, thisArg)
|
||||
}
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public filter<S extends T>(predicate: (value: Static<T>, index: number, array: Static<T>[]) => value is Static<S>, thisArg?: any): Static<S>[]
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
public filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[]
|
||||
public filter(predicate: any, thisArg: any): any {
|
||||
return this.#values.filter(predicate as any, thisArg)
|
||||
}
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
||||
*/
|
||||
public reduce(callbackfn: (previousValue: Static<T>, currentValue: Static<T>, currentIndex: number, array: T[]) => Static<T>): Static<T>
|
||||
public reduce(callbackfn: (previousValue: Static<T>, currentValue: Static<T>, currentIndex: number, array: T[]) => Static<T>, initialValue: Static<T>): Static<T>
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
||||
*/
|
||||
public reduce<U>(callbackfn: (previousValue: U, currentValue: Static<T>, currentIndex: number, array: Static<T>[]) => U, initialValue: U): U
|
||||
public reduce(callbackfn: any, initialValue?: any): any {
|
||||
return this.#values.reduce(callbackfn, initialValue)
|
||||
}
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
||||
*/
|
||||
public reduceRight(callbackfn: (previousValue: Static<T>, currentValue: Static<T>, currentIndex: number, array: Static<T>[]) => Static<T>): Static<T>
|
||||
public reduceRight(callbackfn: (previousValue: Static<T>, currentValue: Static<T>, currentIndex: number, array: Static<T>[]) => Static<T>, initialValue: T): Static<T>
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
|
||||
*/
|
||||
public reduceRight<U>(callbackfn: (previousValue: U, currentValue: Static<T>, currentIndex: number, array: Static<T>[]) => U, initialValue: U): U
|
||||
public reduceRight(callbackfn: any, initialValue?: any): any {
|
||||
return this.#values.reduceRight(callbackfn, initialValue)
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Assertions
|
||||
// ---------------------------------------------------
|
||||
#formatError(errors: ValueError[]) {
|
||||
return errors.map((error) => `${error.message} ${error.path}`).join('. ')
|
||||
}
|
||||
/** Asserts the given values */
|
||||
#assertIndexInBounds(index: number) {
|
||||
if (index >= 0 && index < this.#values.length) return
|
||||
throw new TypeArrayError(`Index ${index} is outside the bounds of this Array.`)
|
||||
}
|
||||
/** Asserts the given values */
|
||||
#assertItem(index: number, item: unknown): asserts item is Static<T> {
|
||||
if (this.#typeCheck.Check(item)) return
|
||||
const message = this.#formatError([...this.#typeCheck.Errors(item)])
|
||||
throw new TypeArrayError(`Item at Index ${index} is invalid. ${message}`)
|
||||
}
|
||||
/** Asserts the given values */
|
||||
#assertItems(items: unknown[]): asserts items is Static<T>[] {
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
this.#assertItem(i, items[i])
|
||||
}
|
||||
}
|
||||
/** Creates a typed array from an existing array */
|
||||
public static from<T extends TSchema>(schema: T, iterable: IterableIterator<Static<T>> | Array<Static<T>>): TypeArray<T> {
|
||||
if (globalThis.Array.isArray(iterable)) {
|
||||
const array = new TypeArray(schema, iterable.length)
|
||||
for (let i = 0; i < iterable.length; i++) {
|
||||
array.set(i, iterable[i])
|
||||
}
|
||||
return array
|
||||
}
|
||||
const array = new TypeArray(schema)
|
||||
for (const value of iterable) {
|
||||
array.push(value)
|
||||
}
|
||||
return array
|
||||
}
|
||||
}
|
||||
31
example/collections/index.ts
Normal file
31
example/collections/index.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/collections
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2025 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
|
||||
export * from './array'
|
||||
export * from './map'
|
||||
export * from './set'
|
||||
156
example/collections/map.ts
Normal file
156
example/collections/map.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/collections
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2025 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
|
||||
import { TypeCheck, TypeCompiler, ValueError } from '@sinclair/typebox/compiler'
|
||||
import { TSchema, Static, TypeBoxError } from '@sinclair/typebox'
|
||||
import { Value } from '@sinclair/typebox/value'
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// TypeMapKeyError
|
||||
// ----------------------------------------------------------------
|
||||
export class TypeMapKeyError extends TypeBoxError {
|
||||
constructor(message: string) {
|
||||
super(`${message} for key`)
|
||||
}
|
||||
}
|
||||
export class TypeMapValueError extends TypeBoxError {
|
||||
constructor(key: unknown, message: string) {
|
||||
super(`${message} for key ${JSON.stringify(key)}`)
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------------------------
|
||||
// TypeMap<K, V>
|
||||
// ----------------------------------------------------------------
|
||||
// prettier-ignore
|
||||
type TypeMapEntries<K extends TSchema, V extends TSchema> =
|
||||
| Iterable<[Static<K>, Static<V>]>
|
||||
| Array<[Static<K>, Static<V>]>
|
||||
/** Runtime type checked Map collection */
|
||||
export class TypeMap<K extends TSchema, V extends TSchema> {
|
||||
readonly #keycheck: TypeCheck<K>
|
||||
readonly #valuecheck: TypeCheck<V>
|
||||
readonly #keys: Map<bigint, Static<K>>
|
||||
readonly #values: Map<bigint, Static<V>>
|
||||
/** Constructs a new HashMap of the given key and value types. */
|
||||
constructor(key: K, value: V, entries: TypeMapEntries<K, V> = []) {
|
||||
this.#keycheck = TypeCompiler.Compile(key)
|
||||
this.#valuecheck = TypeCompiler.Compile(value)
|
||||
this.#keys = new Map<bigint, Static<K>>()
|
||||
this.#values = new Map<bigint, Static<V>>()
|
||||
for (const [key, value] of entries) {
|
||||
this.set(key, value)
|
||||
}
|
||||
}
|
||||
/** Iterator for this TypeMap */
|
||||
public *[Symbol.iterator](): IterableIterator<[Static<K>, Static<V>]> {
|
||||
for (const [key, value] of this.#values) {
|
||||
yield [this.#keys.get(key)!, value]
|
||||
}
|
||||
}
|
||||
/** Iterator for the keys in this TypeMap */
|
||||
public *keys(): IterableIterator<Static<K>> {
|
||||
yield* this.#keys.values()
|
||||
}
|
||||
/** Iterator for the values in this TypeMap */
|
||||
public *values(): IterableIterator<Static<V>> {
|
||||
yield* this.#values.values()
|
||||
}
|
||||
/** Clears all entries in this map */
|
||||
public clear(): void {
|
||||
this.#values.clear()
|
||||
this.#keys.clear()
|
||||
}
|
||||
/** Executes a provided function once per each key/value pair in the Map, in insertion order. */
|
||||
public forEach(callbackfn: (value: Static<V>, key: Static<K>, map: TypeMap<K, V>) => void, thisArg?: any): void {
|
||||
this.#values.forEach((value, key) => callbackfn(value, this.#keys.get(key)!, this))
|
||||
}
|
||||
/** @returns the number of elements in the TypeMap. */
|
||||
public get size(): number {
|
||||
return this.#values.size
|
||||
}
|
||||
/**
|
||||
* @returns boolean indicating whether an element with the specified key exists or not.
|
||||
*/
|
||||
public has(key: Static<K>): boolean {
|
||||
this.#assertKey(key)
|
||||
return this.#values.has(this.#encodeKey(key))
|
||||
}
|
||||
/**
|
||||
* Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
|
||||
* @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
|
||||
*/
|
||||
public get(key: Static<K>): Static<V> | undefined {
|
||||
this.#assertKey(key)
|
||||
return this.#values.get(this.#encodeKey(key))!
|
||||
}
|
||||
/**
|
||||
* Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
|
||||
*/
|
||||
public set(key: Static<K>, value: Static<V>) {
|
||||
this.#assertKey(key)
|
||||
this.#assertValue(key, value)
|
||||
const encodedKey = this.#encodeKey(key)
|
||||
this.#keys.set(encodedKey, key)
|
||||
this.#values.set(encodedKey, value)
|
||||
}
|
||||
/**
|
||||
* @returns true if an element in the Map existed and has been removed, or false if the element does not exist.
|
||||
*/
|
||||
public delete(key: Static<K>): boolean {
|
||||
this.#assertKey(key)
|
||||
const encodedKey = this.#encodeKey(key)
|
||||
this.#keys.delete(encodedKey)
|
||||
return this.#values.delete(encodedKey)
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Encoder
|
||||
// ---------------------------------------------------
|
||||
/** Encodes the key as a 64bit numeric */
|
||||
#encodeKey(key: Static<K>) {
|
||||
return Value.Hash(key)
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Assertions
|
||||
// ---------------------------------------------------
|
||||
#formatError(errors: ValueError[]) {
|
||||
return errors
|
||||
.map((error) => `${error.message} ${error.path}`)
|
||||
.join('. ')
|
||||
.trim()
|
||||
}
|
||||
/** Asserts the key matches the key schema */
|
||||
#assertKey(key: unknown): asserts key is Static<K> {
|
||||
if (this.#keycheck.Check(key)) return
|
||||
throw new TypeMapKeyError(this.#formatError([...this.#keycheck.Errors(key)]))
|
||||
}
|
||||
/** Asserts the key matches the value schema */
|
||||
#assertValue(key: Static<K>, value: unknown): asserts value is Static<V> {
|
||||
if (this.#valuecheck.Check(value)) return
|
||||
throw new TypeMapValueError(key, this.#formatError([...this.#valuecheck.Errors(value)]))
|
||||
}
|
||||
}
|
||||
3
example/collections/readme.md
Normal file
3
example/collections/readme.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Collections
|
||||
|
||||
This example implements runtime type safe generic `Array`, `Map` and `Set` collection types using TypeBox types as the generic type arguments.
|
||||
109
example/collections/set.ts
Normal file
109
example/collections/set.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/collections
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2025 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
|
||||
import { TypeCheck, TypeCompiler, ValueError } from '@sinclair/typebox/compiler'
|
||||
import { TSchema, Static, TypeBoxError } from '@sinclair/typebox'
|
||||
import { Value } from '@sinclair/typebox/value'
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Errors
|
||||
// ----------------------------------------------------------------
|
||||
export class TypeSetError extends TypeBoxError {
|
||||
constructor(message: string) {
|
||||
super(`${message}`)
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------------------------
|
||||
// TypeSet
|
||||
// ----------------------------------------------------------------
|
||||
/** Runtime type checked Set collection */
|
||||
export class TypeSet<T extends TSchema> {
|
||||
readonly #valuecheck: TypeCheck<T>
|
||||
readonly values: Map<bigint, Static<T>>
|
||||
constructor(schema: T, iterable: Array<T> | Iterable<T> = []) {
|
||||
this.#valuecheck = TypeCompiler.Compile(schema)
|
||||
this.values = new Map<bigint, Static<T>>()
|
||||
for (const value of iterable) {
|
||||
this.add(value)
|
||||
}
|
||||
}
|
||||
/** Adds a value to this set */
|
||||
public add(value: Static<T>): this {
|
||||
this.#assertValue(value)
|
||||
this.values.set(this.#encodeKey(value), value)
|
||||
return this
|
||||
}
|
||||
/** Clears the values in this set */
|
||||
public clear(): void {
|
||||
this.values.clear()
|
||||
}
|
||||
/**
|
||||
* Removes a specified value from the Set.
|
||||
* @returns Returns true if an element in the Set existed and has been removed, or false if the element does not exist.
|
||||
*/
|
||||
public delete(value: Static<T>): boolean {
|
||||
return this.values.delete(this.#encodeKey(value))
|
||||
}
|
||||
/** Executes a provided function once per each value in the Set object, in insertion order. */
|
||||
public forEach(callbackfn: (value: Static<T>, value2: Static<T>, set: TypeSet<T>) => void, thisArg?: any): void {
|
||||
this.values.forEach((value, value2) => callbackfn(value, value2, this), thisArg)
|
||||
}
|
||||
/**
|
||||
* @returns a boolean indicating whether an element with the specified value exists in the Set or not.
|
||||
*/
|
||||
public has(value: Static<T>): boolean {
|
||||
return this.values.has(this.#encodeKey(value))
|
||||
}
|
||||
/**
|
||||
* @returns the number of (unique) elements in Set.
|
||||
*/
|
||||
public get size(): number {
|
||||
return this.values.size
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Encoder
|
||||
// ---------------------------------------------------
|
||||
#encodeKey(value: Static<T>) {
|
||||
return Value.Hash(value)
|
||||
}
|
||||
// ---------------------------------------------------
|
||||
// Assertions
|
||||
// ---------------------------------------------------
|
||||
/** Formats errors */
|
||||
#formatError(errors: ValueError[]) {
|
||||
return errors
|
||||
.map((error) => `${error.message} ${error.path}`)
|
||||
.join('. ')
|
||||
.trim()
|
||||
}
|
||||
/** Asserts the key matches the value schema */
|
||||
#assertValue(value: unknown): asserts value is Static<T> {
|
||||
if (this.#valuecheck.Check(value)) return
|
||||
throw new TypeSetError(this.#formatError([...this.#valuecheck.Errors(value)]))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user