Skip to content

Commit

Permalink
Implement Clean Function
Browse files Browse the repository at this point in the history
  • Loading branch information
sinclairzx81 committed Oct 26, 2023
1 parent 0046aed commit a723662
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 43 deletions.
8 changes: 7 additions & 1 deletion examples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { TypeCompiler } from '@sinclair/typebox/compiler'
import { Value, ValuePointer } from '@sinclair/typebox/value'
import { Type, TypeGuard, Kind, Static, TSchema } from '@sinclair/typebox'

const A = Value.Defaults(Type.String(), null)
const A = Value.Clean(
Type.Object({
x: Type.Number(),
y: Type.Number(),
}),
{ x: 1, z: 3 },
)

console.log(A)
6 changes: 3 additions & 3 deletions src/value/cast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,11 @@ function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any):
// --------------------------------------------------------------------------
// Cast
// --------------------------------------------------------------------------
/** Casts a value into a given type and references. The return value will retain as much information of the original value as possible. */
/** `[Immutable]` Casts a value into a given type. The return value will retain as much information of the original value as possible. */
export function Cast<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: unknown): Types.Static<T>
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. */
/** `[Immutable]` Casts a value into a given type. The return value will retain as much information of the original value as possible. */
export function Cast<T extends Types.TSchema>(schema: T, value: unknown): Types.Static<T>
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. */
/** `[Immutable]` Casts a value into a given type. The return value will retain as much information of the original value as possible. */
export function Cast(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1])
}
6 changes: 3 additions & 3 deletions src/value/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,11 +431,11 @@ function Visit<T extends Types.TSchema>(schema: T, references: Types.TSchema[],
// --------------------------------------------------------------------------
// Check
// --------------------------------------------------------------------------
/** Returns true if the value matches the given type. */
/** Returns true if the value matches the given type */
export function Check<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: unknown): value is Types.Static<T>
/** Returns true if the value matches the given type. */
/** Returns true if the value matches the given type */
export function Check<T extends Types.TSchema>(schema: T, value: unknown): value is Types.Static<T>
/** Returns true if the value matches the given type. */
/** Returns true if the value matches the given type */
export function Check(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1])
}
129 changes: 129 additions & 0 deletions src/value/clean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <[email protected]>
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 { IsString, IsObject, IsArray, IsUndefined } from './guard'
import { Check } from './check'
import { Clone } from './clone'
import { Deref } from './deref'
import * as Types from '../typebox'

// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------
function Default(schema: Types.TSchema, references: Types.TSchema[], value: unknown) {
console.log('hello', value)
return value
}
// --------------------------------------------------------------------------
// Structural
// --------------------------------------------------------------------------
function TArray(schema: Types.TArray, references: Types.TSchema[], value: unknown): any {
if (!IsArray(value)) return Default(schema, references, value)
return value.map((value) => Visit(schema.items, references, value))
}
function TIntersect(schema: Types.TIntersect, references: Types.TSchema[], value: unknown): any {
const values: any[] = schema.allOf.map((schema) => Visit(schema, references, Clone(value)))
return values.reduce((acc, value) => {
return IsObject(value) ? { ...acc, ...value } : value
}, {} as any)
}
function TObject(schema: Types.TObject, references: Types.TSchema[], value: unknown): any {
if (!IsObject(value)) return Default(schema, references, value)
return Object.keys(schema.properties).reduce((acc, key) => {
return key in value ? { ...acc, [key]: Visit(schema.properties[key], references, value[key]) } : acc
}, {})
}
function TRecord(schema: Types.TRecord<any, any>, references: Types.TSchema[], value: unknown): any {
if (!IsObject(value)) return Default(schema, references, value)
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0]
const patternRegExp = new RegExp(patternKey)
return Object.keys(value).reduce((acc, key) => {
return patternRegExp.test(key) ? { ...acc, [key]: Visit(patternSchema, references, value[key]) } : acc
}, {})
}
function TRef(schema: Types.TRef<any>, references: Types.TSchema[], value: unknown): any {
const target = Deref(schema, references)
return Visit(target, references, value)
}
function TThis(schema: Types.TThis, references: Types.TSchema[], value: unknown): any {
const target = Deref(schema, references)
return Visit(target, references, value)
}
function TTuple(schema: Types.TTuple, references: Types.TSchema[], value: unknown): any {
if (!IsArray(value)) return Default(schema, references, value)
if (IsUndefined(schema.items)) return []
return schema.items!.map((schema, index) => Visit(schema, references, value[index]))
}
function TUnion(schema: Types.TUnion, references: Types.TSchema[], value: unknown): any {
for (const inner of schema.anyOf) {
if (!Check(inner, value)) continue
return Visit(inner, references, value)
}
return Default(schema, references, value)
}
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: unknown): unknown {
const references_ = IsString(schema.$id) ? [...references, schema] : references
const schema_ = schema as any
switch (schema_[Types.Kind]) {
// --------------------------------------------------------------
// Structural
// --------------------------------------------------------------
case 'Array':
return TArray(schema_, references_, value)
case 'Intersect':
return TIntersect(schema_, references_, value)
case 'Object':
return TObject(schema_, references_, value)
case 'Record':
return TRecord(schema_, references_, value)
case 'Ref':
return TRef(schema_, references_, value)
case 'This':
return TThis(schema_, references_, value)
case 'Tuple':
return TTuple(schema_, references_, value)
case 'Union':
return TUnion(schema_, references_, value)
// --------------------------------------------------------------
// NonStructural
// --------------------------------------------------------------
default:
return Default(schema_, references_, value)
}
}
// --------------------------------------------------------------------------
// Clean
// --------------------------------------------------------------------------
/** `[Immutable]` Removes unknown property or interior value from the given value. The return value may be invalid and should be checked before use. */
export function Clean<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: unknown): unknown
/** `[Immutable]` Removes unknown property or interior value from the given value. The return value may be invalid and should be checked before use. */
export function Clean<T extends Types.TSchema>(schema: T): unknown
/** `[Immutable]` Removes unknown property or interior value from the given value. The return value may be invalid and should be checked before use. */
export function Clean(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], Clone(args[2])) : Visit(args[0], [], Clone(args[1]))
}
2 changes: 1 addition & 1 deletion src/value/clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function ValueType(value: ValueType): any {
// --------------------------------------------------------------------------
// Clone
// --------------------------------------------------------------------------
/** Returns a clone of the given value */
/** `[Immutable]` Returns a structural clone of the given value */
export function Clone<T extends unknown>(value: T): T {
if (IsArray(value)) return ArrayType(value)
if (IsDate(value)) return DateType(value)
Expand Down
6 changes: 3 additions & 3 deletions src/value/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,11 +289,11 @@ function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any):
// --------------------------------------------------------------------------
// Convert
// --------------------------------------------------------------------------
/** Converts any type mismatched values to their target type if a reasonable conversion is possible. */
/** `[Immutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible */
export function Convert<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: unknown): unknown
/** Converts any type mismatched values to their target type if a reasonable conversion is possible. */
/** `[Immutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible */
export function Convert<T extends Types.TSchema>(schema: T, value: unknown): unknown
/** Converts any type mismatched values to their target type if a reasonable conversion is possible. */
/** `[Immutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible */
export function Convert(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1])
}
10 changes: 5 additions & 5 deletions src/value/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,14 +222,14 @@ function TObject(schema: Types.TObject, references: Types.TSchema[]): any {
)
}
}
function TPromise(schema: Types.TPromise<any>, references: Types.TSchema[]): any {
function TPromise(schema: Types.TPromise, references: Types.TSchema[]): any {
if (HasPropertyKey(schema, 'default')) {
return schema.default
} else {
return Promise.resolve(Visit(schema.item, references))
}
}
function TRecord(schema: Types.TRecord<any, any>, references: Types.TSchema[]): any {
function TRecord(schema: Types.TRecord, references: Types.TSchema[]): any {
const [keyPattern, valueSchema] = Object.entries(schema.patternProperties)[0]
if (HasPropertyKey(schema, 'default')) {
return schema.default
Expand All @@ -242,7 +242,7 @@ function TRecord(schema: Types.TRecord<any, any>, references: Types.TSchema[]):
return {}
}
}
function TRef(schema: Types.TRef<any>, references: Types.TSchema[]): any {
function TRef(schema: Types.TRef, references: Types.TSchema[]): any {
if (HasPropertyKey(schema, 'default')) {
return schema.default
} else {
Expand Down Expand Up @@ -300,7 +300,7 @@ function TThis(schema: Types.TThis, references: Types.TSchema[]): any {
return Visit(Deref(schema, references), references)
}
}
function TTuple(schema: Types.TTuple<any[]>, references: Types.TSchema[]): any {
function TTuple(schema: Types.TTuple, references: Types.TSchema[]): any {
if (HasPropertyKey(schema, 'default')) {
return schema.default
}
Expand All @@ -317,7 +317,7 @@ function TUndefined(schema: Types.TUndefined, references: Types.TSchema[]): any
return undefined
}
}
function TUnion(schema: Types.TUnion<any[]>, references: Types.TSchema[]): any {
function TUnion(schema: Types.TUnion, references: Types.TSchema[]): any {
if (HasPropertyKey(schema, 'default')) {
return schema.default
} else if (schema.anyOf.length === 0) {
Expand Down
10 changes: 5 additions & 5 deletions src/value/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ function TRecord(schema: Types.TRecord<any, any>, references: Types.TSchema[], v
const object = ValueOrDefault(schema, value)
if (!IsObject(object)) return object
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0]
const patternRegexp = new RegExp(patternKey)
const patternRegExp = new RegExp(patternKey)
return Object.getOwnPropertyNames(value).reduce((acc, key) => {
if (patternRegexp.test(key)) {
if (patternRegExp.test(key)) {
const property = Visit(patternSchema, references, object[key])
return { ...acc, [key]: property }
} else {
Expand Down Expand Up @@ -120,11 +120,11 @@ function Visit(schema: Types.TSchema, references: Types.TSchema[], value: unknow
// --------------------------------------------------------------------------
// Default
// --------------------------------------------------------------------------
/** Creates default values for any missing internal properties, elements or values using `default` annotations. The return value should be checked before use. */
/** `[Immutable]` Applies default values for any missing interior properties or value using `default` annotations. The return value may be invalid and should be checked before use. */
export function Defaults<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: unknown): unknown
/** Creates default values for any missing internal properties, elements or values using `default` annotations. The return value should be checked before use. */
/** `[Immutable]` Applies default values for any missing interior properties or value using `default` annotations. The return value may be invalid and should be checked before use. */
export function Defaults<T extends Types.TSchema>(schema: T, value: unknown): unknown
/** Creates default values for any missing internal properties, elements or values using `default` annotations. The return value should be checked before use. */
/** `[Immutable]` Applies default values for any missing interior properties or value using `default` annotations. The return value may be invalid and should be checked before use. */
export function Defaults(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], Clone(args[2])) : Visit(args[0], [], Clone(args[1]))
}
3 changes: 3 additions & 0 deletions src/value/delta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ function* Visit(path: string, current: unknown, next: unknown): IterableIterator
// ---------------------------------------------------------------------
// Diff
// ---------------------------------------------------------------------
/** Returns edits to transform the current value into the next value */
export function Diff(current: unknown, next: unknown): Edit[] {
return [...Visit('', current, next)]
}
Expand All @@ -150,6 +151,8 @@ function IsRootUpdate(edits: Edit[]): edits is [Update] {
function IsIdentity(edits: Edit[]) {
return edits.length === 0
}

/** `[Immutable]` Returns a new value with edits applied to the given value */
export function Patch<T = any>(current: unknown, edits: Edit[]): T {
if (IsRootUpdate(edits)) {
return Clone(edits[0].value) as T
Expand Down
2 changes: 1 addition & 1 deletion src/value/equal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function ValueType(left: ValueType, right: unknown): any {
// --------------------------------------------------------------------------
// Equal
// --------------------------------------------------------------------------
/** Returns true if the left value deep-equals the right */
/** Returns true if left and right values are structurally equal */
export function Equal<T>(left: T, right: unknown): right is T {
if (IsPlainObject(left)) return ObjectType(left, right)
if (IsDate(left)) return DateType(left, right)
Expand Down
2 changes: 1 addition & 1 deletion src/value/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ function FNV1A64(byte: number) {
// --------------------------------------------------------------------------
// Hash
// --------------------------------------------------------------------------
/** Creates a FNV1A-64 non cryptographic hash of the given value */
/** Returns a FNV1A-64 non cryptographic hash of the given value */
export function Hash(value: unknown) {
Accumulator = BigInt('14695981039346656037')
Visit(value)
Expand Down
2 changes: 1 addition & 1 deletion src/value/mutate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ function IsMismatchedValue(current: unknown, next: unknown) {
// --------------------------------------------------------------------------
// Mutate
// --------------------------------------------------------------------------
/** Performs a deep mutable value assignment while retaining internal references */
/** `[Mutable]` Performs a deep mutable value assignment while retaining internal references. */
export function Mutate(current: Mutable, next: Mutable): void {
if (IsNonMutableValue(current) || IsNonMutableValue(next)) throw new ValueMutateInvalidRootMutationError()
if (IsMismatchedValue(current, next)) throw new ValueMutateTypeMismatchError()
Expand Down
1 change: 1 addition & 0 deletions src/value/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ THE SOFTWARE.
import { IsString, IsPlainObject, IsArray, IsValueType } from './guard'
import { ValueError } from '../errors/errors'
import { Deref } from './deref'
import { Clone } from './clone'
import * as Types from '../typebox'

// -------------------------------------------------------------------------
Expand Down
Loading

0 comments on commit a723662

Please sign in to comment.