diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 3fdb5d7a3c..cf070bdb9e 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -218,7 +218,7 @@ export declare namespace Cause { * @since 4.0.0 * @category models */ - export interface FailureProto extends Inspectable { + export interface FailureProto extends Inspectable, Equal { readonly [FailureTypeId]: typeof FailureTypeId readonly _tag: Tag readonly annotations: ReadonlyMap diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index d0e2c44088..08901a4d91 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -471,7 +471,7 @@ export const unbounded = (): Effect> => make() * @category offering * @since 4.0.0 */ -export const offer = (self: Queue, message: A): Effect => +export const offer = (self: Queue, message: Types.NoInfer): Effect => internalEffect.suspend(() => { if (self.state._tag !== "Open") { return exitFalse @@ -526,7 +526,7 @@ export const offer = (self: Queue, message: A): Effect => * @category offering * @since 4.0.0 */ -export const offerUnsafe = (self: Queue, message: A): boolean => { +export const offerUnsafe = (self: Queue, message: Types.NoInfer): boolean => { if (self.state._tag !== "Open") { return false } else if (self.messages.length >= self.capacity) { diff --git a/packages/effect/src/ServiceMap.ts b/packages/effect/src/ServiceMap.ts index a0b0bcf9dc..44700ca2d8 100644 --- a/packages/effect/src/ServiceMap.ts +++ b/packages/effect/src/ServiceMap.ts @@ -367,7 +367,7 @@ const Proto: Omit, "mapUnsafe"> = { return true }, [Hash.symbol](this: ServiceMap): number { - return Hash.cached(this, () => Hash.number(this.mapUnsafe.size)) + return Hash.number(this.mapUnsafe.size) } } diff --git a/packages/effect/src/batching/Request.ts b/packages/effect/src/batching/Request.ts index 7714b802ed..fc7ed7b939 100644 --- a/packages/effect/src/batching/Request.ts +++ b/packages/effect/src/batching/Request.ts @@ -19,7 +19,6 @@ import type * as Effect from "../Effect.ts" import type * as Exit from "../Exit.ts" import { dual } from "../Function.ts" import * as core from "../internal/core.ts" -import { StructuralPrototype } from "../internal/core.ts" import * as internalEffect from "../internal/effect.ts" import type * as ServiceMap from "../ServiceMap.ts" import type * as Types from "../types/Types.ts" @@ -178,7 +177,6 @@ const requestVariance = { * @since 4.0.0 */ export const RequestPrototype: Request = { - ...StructuralPrototype, [TypeId]: requestVariance } diff --git a/packages/effect/src/collections/Chunk.ts b/packages/effect/src/collections/Chunk.ts index 8cd1c744ad..48850116a5 100644 --- a/packages/effect/src/collections/Chunk.ts +++ b/packages/effect/src/collections/Chunk.ts @@ -253,7 +253,7 @@ const ChunkProto: Omit, "backing" | "depth" | "left" | "length" | return isChunk(that) && _equivalence(this, that) }, [Hash.symbol](this: Chunk): number { - return Hash.cached(this, () => Hash.array(toReadonlyArray(this))) + return Hash.array(toReadonlyArray(this)) }, [Symbol.iterator](this: Chunk): Iterator { switch (this.backing._tag) { diff --git a/packages/effect/src/collections/MutableHashMap.ts b/packages/effect/src/collections/MutableHashMap.ts index cf05bada8f..ada4918ba7 100644 --- a/packages/effect/src/collections/MutableHashMap.ts +++ b/packages/effect/src/collections/MutableHashMap.ts @@ -66,7 +66,7 @@ const TypeId = "~effect/collections/MutableHashMap" export interface MutableHashMap extends Iterable<[K, V]>, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId readonly backing: Map - readonly buckets: Map> + readonly buckets: Map> } const MutableHashMapProto: Omit, "backing" | "buckets" | "bucketsSize"> = { @@ -208,14 +208,14 @@ export const get: { >(2, (self: MutableHashMap, key: K): Option.Option => { if (self.backing.has(key)) { return Option.some(self.backing.get(key)!) - } else if (Equal.isEqual(key) === false) { + } else if (isSimpleKey(key)) { return Option.none() } const refKey = referentialKeysCache.get(self) if (refKey !== undefined) { return self.backing.has(refKey) ? Option.some(self.backing.get(refKey)!) : Option.none() } - const hash = key[Hash.symbol]() + const hash = Hash.hash(key) const bucket = self.buckets.get(hash) if (bucket === undefined) { return Option.none() @@ -224,6 +224,7 @@ export const get: { }) const referentialKeysCache = new WeakMap() +const isSimpleKey = (u: unknown): boolean => typeof u !== "object" && typeof u !== "function" /** * Extracts all keys from the MutableHashMap into an array. @@ -282,11 +283,11 @@ export const values = (self: MutableHashMap): Iterable => self.ba const getFromBucket = ( self: MutableHashMap, - bucket: NonEmptyArray, - key: K & Equal.Equal + bucket: NonEmptyArray, + key: K ): Option.Option => { for (let i = 0, len = bucket.length; i < len; i++) { - if (key[Equal.symbol](bucket[i])) { + if (Equal.equals(key, bucket[i])) { const refKey = bucket[i] referentialKeysCache.set(key, refKey) return Option.some(self.backing.get(refKey)!) @@ -360,7 +361,7 @@ export const set: { (key: K, value: V) => (self: MutableHashMap) => MutableHashMap, (self: MutableHashMap, key: K, value: V) => MutableHashMap >(3, (self: MutableHashMap, key: K, value: V) => { - if (self.backing.has(key) || Equal.isEqual(key) === false) { + if (self.backing.has(key) || isSimpleKey(key)) { self.backing.set(key, value) return self } @@ -370,7 +371,7 @@ export const set: { return self } - const hash = key[Hash.symbol]() + const hash = Hash.hash(key) const bucket = self.buckets.get(hash) if (bucket === undefined) { self.buckets.set(hash, [key]) @@ -388,11 +389,11 @@ export const set: { }) const getRefKey = ( - bucket: NonEmptyArray, - key: K & Equal.Equal + bucket: NonEmptyArray, + key: K ) => { for (let i = 0, len = bucket.length; i < len; i++) { - if (key[Equal.symbol](bucket[i])) { + if (Equal.equals(key, bucket[i])) { referentialKeysCache.set(key, bucket[i]) return bucket[i] } @@ -437,7 +438,7 @@ export const modify: { (self: MutableHashMap, key: K, f: (v: V) => V) => MutableHashMap >(3, (self: MutableHashMap, key: K, f: (v: V) => V) => { const hasKey = self.backing.has(key) - if (hasKey || Equal.isEqual(key) === false) { + if (hasKey || isSimpleKey(key)) { if (hasKey) { self.backing.set(key, f(self.backing.get(key)!)) } @@ -449,7 +450,7 @@ export const modify: { return self } - const hash = key[Hash.symbol]() + const hash = Hash.hash(key) const bucket = self.buckets.get(hash) if (bucket === undefined) { return self @@ -569,20 +570,20 @@ export const remove: { (key: K) => (self: MutableHashMap) => MutableHashMap, (self: MutableHashMap, key: K) => MutableHashMap >(2, (self: MutableHashMap, key_: K) => { - if (Equal.isEqual(key_) === false) { + if (isSimpleKey(key_)) { self.backing.delete(key_) return self } const key = referentialKeysCache.get(self) ?? key_ - const hash = key[Hash.symbol]() + const hash = Hash.hash(key) const bucket = self.buckets.get(hash) if (bucket === undefined) { return self } for (let i = 0, len = bucket.length; i < len; i++) { const bkey = bucket[i] - if (bkey === key || key[Equal.symbol](bkey)) { + if (bkey === key || Equal.equals(key, bkey)) { self.backing.delete(bkey) bucket.splice(i, 1) break diff --git a/packages/effect/src/data/Data.ts b/packages/effect/src/data/Data.ts index 0661895e1f..9119482ff2 100644 --- a/packages/effect/src/data/Data.ts +++ b/packages/effect/src/data/Data.ts @@ -9,327 +9,14 @@ * - **Type safety**: Constructors ensure type safety and consistency * - **Effect integration**: Error types work seamlessly with Effect's error handling * - * @example - * ```ts - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * // Basic struct usage - * const person1 = Data.struct({ name: "Alice", age: 30 }) - * const person2 = Data.struct({ name: "Alice", age: 30 }) - * - * console.log(Equal.equals(person1, person2)) // true - * console.log(person1 === person2) // false (different references) - * - * // Regular objects don't have structural equality - * const obj1 = { name: "Alice", age: 30 } - * const obj2 = { name: "Alice", age: 30 } - * console.log(Equal.equals(obj1, obj2)) // false - * - * // Tagged enums for discriminated unions - * const { Success, Failure, $match } = Data.taggedEnum< - * | { _tag: "Success"; value: number } - * | { _tag: "Failure"; error: string } - * >() - * - * const result1 = Success({ value: 42 }) - * const result2 = Failure({ error: "Not found" }) - * - * // Pattern matching - * const message = $match(result1, { - * Success: ({ value }) => `Got value: ${value}`, - * Failure: ({ error }) => `Error: ${error}` - * }) - * ``` - * * @since 2.0.0 */ import type * as Cause from "../Cause.ts" import * as Predicate from "../data/Predicate.ts" import * as core from "../internal/core.ts" -import { StructuralPrototype } from "../internal/core.ts" -import * as internal from "../internal/data.ts" import type * as Types from "../types/Types.ts" import type { Unify } from "../types/Unify.ts" -/** - * A namespace providing utilities for Case constructors. - * - * This namespace contains types and utilities for creating case constructors - * that provide structural equality semantics for data types. - * - * @example - * ```ts - * import { Data } from "effect/data" - * - * interface User { - * readonly name: string - * readonly age: number - * } - * - * const User = Data.case() - * - * const user1 = User({ name: "Alice", age: 30 }) - * const user2 = User({ name: "Alice", age: 30 }) - * - * // Structural equality - * console.log(user1 === user2) // false (different references) - * ``` - * - * @since 2.0.0 - * @category types - */ -export declare namespace Case { - /** - * A constructor type for creating Case instances with structural equality. - * - * This type represents a constructor function that takes arguments (excluding - * the specified tag fields) and returns an instance of type `A` with - * structural equality semantics. - * - * @example - * ```ts - * import { Data } from "effect/data" - * - * interface User { - * readonly name: string - * readonly age: number - * } - * - * // Constructor type for User - * type UserConstructor = Data.Case.Constructor - * // Type: (args: { readonly name: string; readonly age: number }) => User - * - * interface TaggedUser { - * readonly _tag: "User" - * readonly name: string - * readonly age: number - * } - * - * // Constructor type for TaggedUser (excluding _tag field) - * type TaggedUserConstructor = Data.Case.Constructor - * // Type: (args: { readonly name: string; readonly age: number }) => TaggedUser - * ``` - * - * @since 2.0.0 - * @category models - */ - export type Constructor = ( - args: Types.Equals, {}> extends true ? void - : { readonly [P in keyof A as P extends Tag ? never : P]: A[P] } - ) => A -} - -/** - * @example - * ```ts - * import * as assert from "node:assert" - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * const alice = Data.struct({ name: "Alice", age: 30 }) - * - * const bob = Data.struct({ name: "Bob", age: 40 }) - * - * assert.deepStrictEqual(Equal.equals(alice, alice), true) - * assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true) - * - * assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false) - * assert.deepStrictEqual(Equal.equals(alice, bob), false) - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const struct: >( - a: A -) => { readonly [P in keyof A]: A[P] } = internal.struct - -/** - * Create a `Data` struct from an object without copying it. - * - * **Warning**: This function directly modifies the input object's prototype - * to enable structural equality without creating a copy. Use `struct` if you - * need immutability guarantees. - * - * @example - * ```ts - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * const obj = { name: "Alice", age: 30 } - * const person = Data.structUnsafe(obj) - * - * // obj and person reference the same object - * console.log(obj === person) // true - * console.log(Equal.equals(person, Data.struct({ name: "Alice", age: 30 }))) // true - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const structUnsafe = >( - as: A -): { readonly [P in keyof A]: A[P] } => Object.setPrototypeOf(as, StructuralPrototype) - -/** - * Create a `Data` tuple with structural equality from the provided elements. - * - * Unlike regular arrays, `Data` tuples support structural equality comparison - * using the `Equal` module. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * const alice = Data.tuple("Alice", 30) - * const bob = Data.tuple("Bob", 40) - * - * assert.deepStrictEqual(Equal.equals(alice, alice), true) - * assert.deepStrictEqual(Equal.equals(alice, Data.tuple("Alice", 30)), true) - * - * assert.deepStrictEqual(Equal.equals(alice, ["Alice", 30]), false) - * assert.deepStrictEqual(Equal.equals(alice, bob), false) - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const tuple = >(...as: As): Readonly => arrayUnsafe(as) - -/** - * Create a `Data` array with structural equality from the provided array. - * - * This function creates a copy of the input array and enables structural - * equality comparison using the `Equal` module. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * const alice = Data.struct({ name: "Alice", age: 30 }) - * const bob = Data.struct({ name: "Bob", age: 40 }) - * - * const persons = Data.array([alice, bob]) - * - * assert.deepStrictEqual( - * Equal.equals( - * persons, - * Data.array([ - * Data.struct({ name: "Alice", age: 30 }), - * Data.struct({ name: "Bob", age: 40 }) - * ]) - * ), - * true - * ) - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const array = >(as: As): Readonly => arrayUnsafe(as.slice(0) as unknown as As) - -/** - * Create a `Data` array from an array without copying it. - * - * **Warning**: This function directly modifies the input array's prototype - * to enable structural equality without creating a copy. Use `array` if you - * need immutability guarantees. - * - * @example - * ```ts - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * const originalArray = [1, 2, 3] - * const dataArray = Data.arrayUnsafe(originalArray) - * - * // originalArray and dataArray reference the same array - * console.log(originalArray === dataArray) // true - * console.log(Equal.equals(dataArray, Data.array([1, 2, 3]))) // true - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const arrayUnsafe = >( - as: As -): Readonly => Object.setPrototypeOf(as, internal.ArrayProto) - -const _case = (): Case.Constructor => (args) => - (args === undefined - ? Object.create(StructuralPrototype) - : struct(args)) as any - -export { - /** - * Provides a constructor for the specified `Case`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * interface Person { - * readonly name: string - * } - * - * // Creating a constructor for the specified Case - * const Person = Data.case() - * - * // Creating instances of Person - * const mike1 = Person({ name: "Mike" }) - * const mike2 = Person({ name: "Mike" }) - * const john = Person({ name: "John" }) - * - * // Checking equality - * assert.deepStrictEqual(Equal.equals(mike1, mike2), true) - * assert.deepStrictEqual(Equal.equals(mike1, john), false) - * - * ``` - * @since 2.0.0 - * @category constructors - */ - _case as case -} - -/** - * Provides a tagged constructor for the specified `Case`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Data } from "effect/data" - * - * interface Person { - * readonly _tag: "Person" // the tag - * readonly name: string - * } - * - * const Person = Data.tagged("Person") - * - * const mike = Person({ name: "Mike" }) - * - * assert.deepEqual(mike, { _tag: "Person", name: "Mike" }) - * ``` - * - * @since 2.0.0 - * @category constructors - */ -export const tagged = ( - tag: A["_tag"] -): Case.Constructor => -(args) => { - const value = args === undefined ? Object.create(StructuralPrototype) : struct(args) - value._tag = tag - return value -} - /** * Provides a constructor for a Case Class. * @@ -357,7 +44,11 @@ export const tagged = ( export const Class: new = {}>( args: Types.Equals extends true ? void : { readonly [P in keyof A]: A[P] } -) => Readonly = internal.Structural as any +) => Readonly = function(this: any, props: any) { + if (props) { + Object.assign(this, props) + } +} as any /** * Provides a Tagged constructor for a Case Class. @@ -390,39 +81,13 @@ export const TaggedClass = ( ): new = {}>( args: Types.Equals extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] } -) => Readonly & { readonly _tag: Tag } => { - class Base extends Class { - readonly _tag = tag - } - return Base as any -} - -/** - * A base constructor for creating structural data types. - * - * This provides the underlying implementation for creating objects with - * structural equality semantics. - * - * @example - * ```ts - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * class Person extends Data.Structural<{ name: string; age: number }> {} - * - * const person1 = new Person({ name: "Alice", age: 30 }) - * const person2 = new Person({ name: "Alice", age: 30 }) - * - * console.log(Equal.equals(person1, person2)) // true - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const Structural: new( - args: Types.Equals extends true ? void - : { readonly [P in keyof A]: A[P] } -) => {} = internal.Structural as any +) => Readonly & { readonly _tag: Tag } => + function(this: any, props: any) { + this._tag = tag + if (props) { + Object.assign(this, props) + } + } as any /** * Create a tagged enum data type, which is a union of `Data` structs. @@ -691,7 +356,7 @@ export declare namespace TaggedEnum { */ export type Constructor = Types.Simplify< { - readonly [Tag in A["_tag"]]: Case.Constructor< + readonly [Tag in A["_tag"]]: ConstructorFrom< Extract, "_tag" > @@ -723,6 +388,15 @@ export declare namespace TaggedEnum { } > + /** + * @since 4.0.0 + * @category types + */ + export type ConstructorFrom = ( + args: Types.Equals, {}> extends true ? void + : { readonly [P in keyof A as P extends Tag ? never : P]: A[P] } + ) => A + /** * Provides type-safe pattern matching for generic tagged enums. * @@ -906,7 +580,7 @@ export const taggedEnum: { } else if (tag === "$match") { return taggedMatch } - return tagged(tag as string) + return (props: any) => ({ _tag: tag, ...props }) } } ) as any diff --git a/packages/effect/src/data/Redacted.ts b/packages/effect/src/data/Redacted.ts index 011c8ed31e..192d3f2f8a 100644 --- a/packages/effect/src/data/Redacted.ts +++ b/packages/effect/src/data/Redacted.ts @@ -144,7 +144,7 @@ const Proto = { return `` }, [Hash.symbol](this: Redacted): number { - return Hash.cached(this, () => Hash.hash(redactedRegistry.get(this))) + return Hash.hash(redactedRegistry.get(this)) }, [Equal.symbol](this: Redacted, that: unknown): boolean { return ( diff --git a/packages/effect/src/data/index.ts b/packages/effect/src/data/index.ts index 4c87bb3cc4..8d9911c838 100644 --- a/packages/effect/src/data/index.ts +++ b/packages/effect/src/data/index.ts @@ -44,39 +44,6 @@ export * as Combiner from "./Combiner.ts" * - **Type safety**: Constructors ensure type safety and consistency * - **Effect integration**: Error types work seamlessly with Effect's error handling * - * @example - * ```ts - * import { Equal } from "effect/interfaces" - * import { Data } from "effect/data" - * - * // Basic struct usage - * const person1 = Data.struct({ name: "Alice", age: 30 }) - * const person2 = Data.struct({ name: "Alice", age: 30 }) - * - * console.log(Equal.equals(person1, person2)) // true - * console.log(person1 === person2) // false (different references) - * - * // Regular objects don't have structural equality - * const obj1 = { name: "Alice", age: 30 } - * const obj2 = { name: "Alice", age: 30 } - * console.log(Equal.equals(obj1, obj2)) // false - * - * // Tagged enums for discriminated unions - * const { Success, Failure, $match } = Data.taggedEnum< - * | { _tag: "Success"; value: number } - * | { _tag: "Failure"; error: string } - * >() - * - * const result1 = Success({ value: 42 }) - * const result2 = Failure({ error: "Not found" }) - * - * // Pattern matching - * const message = $match(result1, { - * Success: ({ value }) => `Got value: ${value}`, - * Failure: ({ error }) => `Error: ${error}` - * }) - * ``` - * * @since 2.0.0 */ export * as Data from "./Data.ts" diff --git a/packages/effect/src/interfaces/Equal.ts b/packages/effect/src/interfaces/Equal.ts index 354ae77061..2293b88d67 100644 --- a/packages/effect/src/interfaces/Equal.ts +++ b/packages/effect/src/interfaces/Equal.ts @@ -8,6 +8,16 @@ import type { Equivalence } from "../data/Equivalence.ts" import { hasProperty } from "../data/Predicate.ts" import * as Hash from "../interfaces/Hash.ts" +import { byReferenceInstances, getAllObjectKeys } from "../internal/equal.ts" + +/** @internal */ +const visitedLeft = new WeakSet() + +/** @internal */ +const visitedRight = new WeakSet() + +/** @internal */ +const equalityCache = new WeakMap>() /** * The unique identifier used to identify objects that implement the `Equal` interface. @@ -47,29 +57,63 @@ export interface Equal extends Hash.Hash { } /** - * Compares two values for equality. Returns `true` if the values are equal, `false` otherwise. + * Compares two values for structural equality. Returns `true` if the values are structurally equal, `false` otherwise. * - * For objects implementing the `Equal` interface, uses their custom equality logic. - * For `Date` objects, compares their ISO string representations. - * For other values, uses reference equality and type checking. + * This function performs deep structural comparison: + * - For primitive values: uses value equality (including NaN === NaN) + * - For objects implementing `Equal` interface: uses their custom equality logic + * - For Date objects: compares ISO string representations + * - For RegExp objects: compares string representations + * - For Arrays: recursively compares each element + * - For Maps: compares keys and values structurally (order-independent) + * - For Sets: compares values structurally (order-independent) + * - For plain objects: compares all properties recursively + * - Handles circular references correctly + * + * **Performance**: Results of object comparisons are cached using WeakMaps to optimize + * repeated equality checks between the same object pairs. + * + * **⚠️ CRITICAL IMMUTABILITY REQUIREMENT**: Objects being compared must be treated as + * immutable after their first equality computation. Equality results are cached, so + * mutating an object after comparison will lead to stale cached values and incorrect + * equality results. For mutable objects, use referential equality by implementing + * custom `Equal` interface that compares object references, not content. + * + * **FORBIDDEN**: Modifying objects after `Equal.equals()` has been called on them + * **ALLOWED**: Using immutable objects, or mutable objects with custom `Equal` interface + * that uses referential equality (compares object references, not content) * * @example * ```ts * import { Equal } from "effect/interfaces" + * import * as assert from "node:assert" * - * // Basic equality - * console.log(Equal.equals(1, 1)) // true - * console.log(Equal.equals(1, 2)) // false + * // Primitive values + * assert(Equal.equals(1, 1) === true) + * assert(Equal.equals(NaN, NaN) === true) * - * // Date equality + * // Objects - structural comparison + * assert(Equal.equals({ a: 1, b: 2 }, { a: 1, b: 2 }) === true) + * assert(Equal.equals({ a: 1 }, { a: 1, b: 2 }) === false) + * + * // Arrays - recursive comparison + * assert(Equal.equals([1, [2, 3]], [1, [2, 3]]) === true) + * assert(Equal.equals([1, 2], [1, 3]) === false) + * + * // Date equality by ISO string * const date1 = new Date("2023-01-01") * const date2 = new Date("2023-01-01") - * console.log(Equal.equals(date1, date2)) // true + * assert(Equal.equals(date1, date2) === true) + * + * // Maps and Sets - structural comparison + * const map1 = new Map([["a", 1], ["b", 2]]) + * const map2 = new Map([["b", 2], ["a", 1]]) // different order + * assert(Equal.equals(map1, map2) === true) * * // Curried version * const isEqualTo5 = Equal.equals(5) - * console.log(isEqualTo5(5)) // true - * console.log(isEqualTo5(3)) // false + * assert(isEqualTo5(5) === true) + * assert(isEqualTo5(3) === false) * ``` * * @category equality @@ -84,24 +128,188 @@ export function equals(): any { return compareBoth(arguments[0], arguments[1]) } -function compareBoth(self: unknown, that: unknown): boolean { - if (self === that) { - return true +/** Helper to run comparison with proper visited tracking */ +function withVisitedTracking( + self: object, + that: object, + fn: () => boolean +): boolean { + const hasLeft = visitedLeft.has(self) + const hasRight = visitedRight.has(that) + // Check for circular references before adding + if (hasLeft && hasRight) { + return true // Both are circular at the same level } + if (hasLeft || hasRight) { + return false // Only one is circular + } + visitedLeft.add(self) + visitedRight.add(that) + const result = fn() + visitedLeft.delete(self) + visitedRight.delete(that) + return result +} + +/** Helper to perform cached object comparison */ +function compareObjectsCached(self: object, that: object): boolean { + // Check cache first + const selfMap = equalityCache.get(self) + if (selfMap?.has(that)) { + return selfMap.get(that)! + } + + // Perform the comparison + let result: boolean + if (Hash.hash(self) !== Hash.hash(that)) { + result = false + } else if (self instanceof Date) { + if (!(that instanceof Date)) { + result = false + } else { + result = self.toISOString() === that.toISOString() + } + } else if (self instanceof RegExp) { + if (!(that instanceof RegExp)) { + result = false + } else { + result = self.toString() === that.toString() + } + } else { + const selfIsEqual = isEqual(self) + const thatIsEqual = isEqual(that) + if (selfIsEqual !== thatIsEqual) { + result = false + } else { + const bothEquals = selfIsEqual && thatIsEqual + if (typeof self === "function" && !bothEquals) { + result = false + } else { + result = withVisitedTracking(self, that, () => { + if (bothEquals) { + return (self as any)[symbol](that) + } else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) { + return false + } + return compareArrays(self, that) + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) { + return false + } + return compareMaps(self, that) + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) { + return false + } + return compareSets(self, that) + } + return compareObjects(self as any, that as any) + }) + } + } + } + + // Cache the result bidirectionally + let selfMap2 = equalityCache.get(self) + if (!selfMap2) { + selfMap2 = new WeakMap() + equalityCache.set(self, selfMap2) + } + selfMap2.set(that, result) + + let thatMap = equalityCache.get(that) + if (!thatMap) { + thatMap = new WeakMap() + equalityCache.set(that, thatMap) + } + thatMap.set(self, result) + + return result +} + +function compareBoth(self: unknown, that: unknown): boolean { + if (self === that) return true + if (self == null || that == null) return false const selfType = typeof self if (selfType !== typeof that) { return false } - if (selfType === "object" || selfType === "function") { - if (self !== null && that !== null) { - if (isEqual(self) && isEqual(that)) { - return Hash.hash(self) === Hash.hash(that) && self[symbol](that) - } else if (self instanceof Date && that instanceof Date) { - return self.toISOString() === that.toISOString() - } + // Special case for NaN: NaN should be considered equal to NaN + if (selfType === "number" && self !== self && that !== that) { + return true + } + if (selfType !== "object" && selfType !== "function") { + return false + } + + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) { + return false + } + + // For objects and functions, use cached comparison + return compareObjectsCached(self as object, that as object) +} + +function compareArrays(self: Array, that: Array): boolean { + for (let i = 0; i < self.length; i++) { + if (!compareBoth(self[i], that[i])) { + return false } } - return false + + return true +} + +function compareObjects(self: Record, that: Record): boolean { + const selfKeys = getAllObjectKeys(self) + const thatKeys = getAllObjectKeys(that) + + if (selfKeys.size !== thatKeys.size) { + return false + } + + for (const key of selfKeys) { + if (!(thatKeys.has(key)) || !compareBoth(self[key], that[key])) { + return false + } + } + + return true +} + +function compareMaps(self: Map, that: Map): boolean { + for (const [selfKey, selfValue] of self) { + let found = false + for (const [thatKey, thatValue] of that) { + if (compareBoth(selfKey, thatKey) && compareBoth(selfValue, thatValue)) { + found = true + break + } + } + if (!found) { + return false + } + } + + return true +} + +function compareSets(self: Set, that: Set): boolean { + for (const selfValue of self) { + let found = false + for (const thatValue of that) { + if (compareBoth(selfValue, thatValue)) { + found = true + break + } + } + if (!found) { + return false + } + } + + return true } /** @@ -110,6 +318,7 @@ function compareBoth(self: unknown, that: unknown): boolean { * @example * ```ts * import { Equal, Hash } from "effect/interfaces" + * import * as assert from "node:assert" * * class MyClass implements Equal.Equal { * [Equal.symbol](that: Equal.Equal): boolean { @@ -121,9 +330,9 @@ function compareBoth(self: unknown, that: unknown): boolean { * } * * const instance = new MyClass() - * console.log(Equal.isEqual(instance)) // true - * console.log(Equal.isEqual({})) // false - * console.log(Equal.isEqual(42)) // false + * assert(Equal.isEqual(instance) === true) + * assert(Equal.isEqual({}) === false) + * assert(Equal.isEqual(42) === false) * ``` * * @category guards @@ -149,3 +358,76 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) * @since 2.0.0 */ export const equivalence: () => Equivalence = () => equals + +/** + * Creates a proxy of an object that uses reference equality instead of structural equality. + * + * By default, plain objects and arrays use structural equality. This function creates + * a proxy that behaves exactly like the original object but uses reference equality + * for comparison purposes. + * + * @example + * ```ts + * import { Equal } from "effect/interfaces" + * import * as assert from "node:assert" + * + * const obj1 = { a: 1, b: 2 } + * const obj2 = { a: 1, b: 2 } + * + * // Normal structural equality + * assert(Equal.equals(obj1, obj2) === true) + * + * // Create reference equality version + * const obj1ByRef = Equal.byReference(obj1) + * assert(Equal.equals(obj1ByRef, obj2) === false) // uses reference equality + * assert(Equal.equals(obj1ByRef, obj1ByRef) === true) // same reference + * + * // Each call creates a new proxy instance + * const obj1ByRef2 = Equal.byReference(obj1) + * assert(Equal.equals(obj1ByRef, obj1ByRef2) === false) // different instances + * + * // Proxy behaves like the original + * assert(obj1ByRef.a === 1) + * ``` + * + * @category utility + * @since 2.0.0 + */ +export const byReference = (obj: T): T => { + const p = new Proxy(obj, {}) + byReferenceInstances.add(p) + return p as T +} + +/** + * Marks an object to use reference equality instead of structural equality, without creating a proxy. + * + * Unlike `byReference`, this function directly modifies the object's equality behavior + * without creating a proxy wrapper. This is more performant but "unsafe" because + * it permanently changes how the object is compared. + * + * @example + * ```ts + * import { Equal } from "effect/interfaces" + * import * as assert from "node:assert" + * + * const obj1 = { a: 1, b: 2 } + * const obj2 = { a: 1, b: 2 } + * + * // Mark obj1 for reference equality (modifies obj1 directly) + * const obj1ByRef = Equal.byReferenceUnsafe(obj1) + * assert(obj1ByRef === obj1) // Same object, no proxy created + * assert(Equal.equals(obj1ByRef, obj2) === false) // uses reference equality + * assert(Equal.equals(obj1ByRef, obj1ByRef) === true) // same reference + * + * // The original obj1 is now permanently marked for reference equality + * assert(Equal.equals(obj1, obj2) === false) // obj1 uses reference equality + * ``` + * + * @category utility + * @since 2.0.0 + */ +export const byReferenceUnsafe = (obj: T): T => { + byReferenceInstances.add(obj) + return obj +} diff --git a/packages/effect/src/interfaces/Hash.ts b/packages/effect/src/interfaces/Hash.ts index 1c0023d8e1..f7fb3a745b 100644 --- a/packages/effect/src/interfaces/Hash.ts +++ b/packages/effect/src/interfaces/Hash.ts @@ -9,9 +9,26 @@ */ import { hasProperty } from "../data/Predicate.ts" import { dual, pipe } from "../Function.ts" +import { byReferenceInstances, getAllObjectKeys } from "../internal/equal.ts" /** @internal */ -const randomHashCache = new WeakMap() +const randomHashCache = new WeakMap() + +/** @internal */ +const hashCache = new WeakMap() + +/** @internal */ +const visitedObjects = new WeakSet() + +function withVisitedTracking(obj: object, fn: () => T): T { + if (visitedObjects.has(obj)) { + return string("[Circular]") as T + } + visitedObjects.add(obj) + const result = fn() + visitedObjects.delete(obj) + return result +} /** * The unique identifier used to identify objects that implement the Hash interface. @@ -56,6 +73,16 @@ export interface Hash { * objects, arrays, and other complex data structures. It automatically handles * different types and provides a consistent hash value for equivalent inputs. * + * **⚠️ CRITICAL IMMUTABILITY REQUIREMENT**: Objects being hashed must be treated as + * immutable after their first hash computation. Hash results are cached, so mutating + * an object after hashing will lead to stale cached values and broken hash-based + * operations. For mutable objects, use referential equality by implementing custom + * `Hash` interface that hashes the object reference, not its content. + * + * **FORBIDDEN**: Modifying objects after `Hash.hash()` has been called on them + * **ALLOWED**: Using immutable objects, or mutable objects with custom `Hash` interface + * that uses referential equality (hashes the object reference, not content) + * * @example * ```ts * import { Hash } from "effect/interfaces" @@ -93,11 +120,32 @@ export const hash: (self: A) => number = (self: A) => { if (self === null) { return string("null") } else if (self instanceof Date) { - return hash(self.toISOString()) - } else if (isHash(self)) { - return self[symbol]() + return string(self.toISOString()) + } else if (self instanceof RegExp) { + return string(self.toString()) } else { - return random(self) + if (byReferenceInstances.has(self)) { + return random(self) + } + if (hashCache.has(self)) { + return hashCache.get(self)! + } + const h = withVisitedTracking(self, () => { + if (isHash(self)) { + return self[symbol]() + } else if (typeof self === "function") { + return random(self) + } else if (Array.isArray(self)) { + return hashArray(self) + } else if (self instanceof Map) { + return hashMap(self) + } else if (self instanceof Set) { + return hashSet(self) + } + return hashStructure(self) + }) + hashCache.set(self, h) + return h } } default: @@ -223,7 +271,7 @@ export const isHash = (u: unknown): u is Hash => hasProperty(u, symbol) * Computes a hash value for a number. * * This function creates a hash value for numeric inputs, handling special cases - * like NaN and Infinity. It uses bitwise operations to ensure good distribution + * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution * of hash values across different numeric inputs. * * @example @@ -232,7 +280,7 @@ export const isHash = (u: unknown): u is Hash => hasProperty(u, symbol) * * console.log(Hash.number(42)) // hash of 42 * console.log(Hash.number(3.14)) // hash of 3.14 - * console.log(Hash.number(NaN)) // 0 (special case) + * console.log(Hash.number(NaN)) // hash of "NaN" * console.log(Hash.number(Infinity)) // 0 (special case) * * // Same numbers produce the same hash @@ -243,8 +291,14 @@ export const isHash = (u: unknown): u is Hash => hasProperty(u, symbol) * @since 2.0.0 */ export const number = (n: number) => { - if (n !== n || n === Infinity) { - return 0 + if (n !== n) { + return string("NaN") + } + if (n === Infinity) { + return string("Infinity") + } + if (n === -Infinity) { + return string("-Infinity") } let h = n | 0 if (h !== n) { @@ -318,7 +372,15 @@ export const string = (str: string) => { export const structureKeys = (o: A, keys: ReadonlyArray) => { let h = 12289 for (let i = 0; i < keys.length; i++) { - h ^= pipe(string(keys[i]! as string), combine(hash((o as any)[keys[i]!]))) + h ^= pipe(hash(keys[i]!), combine(hash((o as any)[keys[i]!]))) + } + return optimize(h) +} + +const hashStructure = (o: A) => { + let h = 12289 + for (const key of getAllObjectKeys(o)) { + h ^= pipe(hash(key), combine(hash((o as any)[key]))) } return optimize(h) } @@ -350,7 +412,7 @@ export const structureKeys = (o: A, keys: ReadonlyArray(o: A) => - structureKeys(o, Object.keys(o) as unknown as ReadonlyArray) + structureKeys(o, getAllObjectKeys(o) as unknown as ReadonlyArray) /** * Computes a hash value for an array by hashing all of its elements. @@ -387,54 +449,22 @@ export const array = (arr: ReadonlyArray) => { return optimize(h) } -const hashCache = new WeakMap() +const hashArray = (arr: ReadonlyArray) => { + return array(arr) +} -/** - * Caches the result of a hash computation for an object. - * - * This function provides a caching mechanism for expensive hash computations. - * The computed hash value is stored in a WeakMap, so the same object will - * always return the same cached hash value, avoiding recomputation. - * - * @example - * ```ts - * import { Hash } from "effect/interfaces" - * - * const obj = { complex: "data structure" } - * - * // Using curried form - * const getCachedHash = Hash.cached(obj) - * const hash1 = getCachedHash(() => Hash.structure(obj)) - * const hash2 = getCachedHash(() => Hash.structure(obj)) // returns cached value - * - * // Using direct form - * const hash3 = Hash.cached(obj, () => Hash.structure(obj)) - * const hash4 = Hash.cached(obj, () => Hash.structure(obj)) // returns cached value - * - * console.log(hash1 === hash2) // true - * console.log(hash3 === hash4) // true - * ``` - * - * @category hashing - * @since 2.0.0 - */ -export const cached: { - (self: object): (hash: () => number) => number - (self: object, hash: () => number): number -} = function() { - if (arguments.length === 1) { - const self = arguments[0] as object - return function(hash: () => number) { - if (!hashCache.has(self)) { - hashCache.set(self, hash()) - } - return hashCache.get(self) - } as any +const hashMap = (map: Map) => { + let h = string("Map") + for (const [key, value] of map) { + h ^= combine(hash(key), hash(value)) } - const self = arguments[0] as object - const hash = arguments[1] as () => number - if (!hashCache.has(self)) { - hashCache.set(self, hash()) + return optimize(h) +} + +const hashSet = (set: Set) => { + let h = string("Set") + for (const value of set) { + h ^= hash(value) } - return hashCache.get(self) + return optimize(h) } diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index 4a173fe06a..edf384ed98 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -103,30 +103,6 @@ export const EffectProto = { } } -/** @internal */ -export const StructuralPrototype: Equal.Equal = { - [Hash.symbol]() { - return Hash.cached(this, () => Hash.structure(this)) - }, - [Equal.symbol](this: Equal.Equal, that: Equal.Equal) { - const selfKeys = Object.keys(this) - const thatKeys = Object.keys(that as object) - if (selfKeys.length !== thatKeys.length) { - return false - } - for (const key of selfKeys) { - if ( - !( - key in (that as object) && - Equal.equals((this as any)[key], (that as any)[key]) - ) - ) { - return false - } - } - return true - } -} /** @internal */ export const isEffect = (u: unknown): u is Effect.Effect => hasProperty(u, EffectTypeId) @@ -186,7 +162,7 @@ export class CauseImpl implements Cause.Cause { ) } [Hash.symbol](): number { - return Hash.cached(this, () => Hash.array(this.failures)) + return Hash.array(this.failures) } } @@ -271,10 +247,9 @@ export class Fail extends FailureBase<"Fail"> implements Cause.Fail { ) } [Hash.symbol](): number { - return Hash.cached(this, () => - Hash.combine(Hash.string(this._tag))( - Hash.combine(Hash.hash(this.error))(Hash.hash(this.annotations)) - )) + return Hash.combine(Hash.string(this._tag))( + Hash.combine(Hash.hash(this.error))(Hash.hash(this.annotations)) + ) } } @@ -324,10 +299,9 @@ export class Die extends FailureBase<"Die"> implements Cause.Die { ) } [Hash.symbol](): number { - return Hash.cached(this, () => - Hash.combine(Hash.string(this._tag))( - Hash.combine(Hash.hash(this.defect))(Hash.hash(this.annotations)) - )) + return Hash.combine(Hash.string(this._tag))( + Hash.combine(Hash.hash(this.defect))(Hash.hash(this.annotations)) + ) } } @@ -500,12 +474,12 @@ export const makeExit = < [Equal.symbol](this: any, that: any): boolean { return ( isExit(that) && - that._tag === options.op && + that._tag === this._tag && Equal.equals(this[args], (that as any)[args]) ) }, [Hash.symbol](this: any): number { - return Hash.cached(this, () => Hash.combine(Hash.string(options.op))(Hash.hash(this[args]))) + return Hash.combine(Hash.string(options.op))(Hash.hash(this[args])) } } return function(value: unknown) { @@ -585,7 +559,7 @@ export const YieldableError: new( return exitFail(this) } } - Object.assign(YieldableError.prototype, StructuralPrototype, YieldableProto) + Object.assign(YieldableError.prototype, YieldableProto) return YieldableError as any })() diff --git a/packages/effect/src/internal/data.ts b/packages/effect/src/internal/data.ts deleted file mode 100644 index 5b046be9af..0000000000 --- a/packages/effect/src/internal/data.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as Equal from "../interfaces/Equal.ts" -import * as Hash from "../interfaces/Hash.ts" -import type * as Types from "../types/Types.ts" -import { StructuralPrototype } from "./core.ts" - -/** @internal */ -export const ArrayProto: Equal.Equal = Object.assign( - Object.create(Array.prototype), - { - [Hash.symbol](this: Array) { - return Hash.cached(this, () => Hash.array(this)) - }, - [Equal.symbol](this: Array, that: Equal.Equal) { - if (Array.isArray(that) && this.length === that.length) { - return this.every((v, i) => Equal.equals(v, (that as Array)[i])) - } else { - return false - } - } - } -) - -/** @internal */ -export const Structural: new( - args: Types.Equals, {}> extends true ? void - : { - readonly [P in keyof A as P extends keyof Equal.Equal ? never : P]: A[P] - } -) => {} = (function() { - function Structural(this: any, args: any) { - if (args) { - Object.assign(this, args) - } - } - Structural.prototype = StructuralPrototype - return Structural as any -})() - -/** @internal */ -export const struct = >>(as: As): As => - Object.assign(Object.create(StructuralPrototype), as) diff --git a/packages/effect/src/internal/dateTime.ts b/packages/effect/src/internal/dateTime.ts index 0b04dd4762..2b66562551 100644 --- a/packages/effect/src/internal/dateTime.ts +++ b/packages/effect/src/internal/dateTime.ts @@ -40,7 +40,7 @@ const ProtoUtc = { ...Proto, _tag: "Utc", [Hash.symbol](this: DateTime.Utc) { - return Hash.cached(this, () => Hash.number(this.epochMillis)) + return Hash.number(this.epochMillis) }, [Equal.symbol](this: DateTime.Utc, that: unknown) { return isDateTime(that) && that._tag === "Utc" && this.epochMillis === that.epochMillis @@ -54,7 +54,7 @@ const ProtoZoned = { ...Proto, _tag: "Zoned", [Hash.symbol](this: DateTime.Zoned) { - return Hash.cached(this, () => Hash.combine(Hash.number(this.epochMillis))(Hash.hash(this.zone))) + return Hash.combine(Hash.number(this.epochMillis))(Hash.hash(this.zone)) }, [Equal.symbol](this: DateTime.Zoned, that: unknown) { return isDateTime(that) && that._tag === "Zoned" && this.epochMillis === that.epochMillis && @@ -76,7 +76,7 @@ const ProtoTimeZoneNamed = { ...ProtoTimeZone, _tag: "Named", [Hash.symbol](this: DateTime.TimeZone.Named) { - return Hash.cached(this, () => Hash.string(`Named:${this.id}`)) + return Hash.string(`Named:${this.id}`) }, [Equal.symbol](this: DateTime.TimeZone.Named, that: unknown) { return isTimeZone(that) && that._tag === "Named" && this.id === that.id @@ -97,7 +97,7 @@ const ProtoTimeZoneOffset = { ...ProtoTimeZone, _tag: "Offset", [Hash.symbol](this: DateTime.TimeZone.Offset) { - return Hash.cached(this, () => Hash.string(`Offset:${this.offset}`)) + return Hash.string(`Offset:${this.offset}`) }, [Equal.symbol](this: DateTime.TimeZone.Offset, that: unknown) { return isTimeZone(that) && that._tag === "Offset" && this.offset === that.offset diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 69cdc0018b..151d5bd9e7 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -108,15 +108,14 @@ export class Interrupt extends FailureBase<"Interrupt"> implements Cause.Interru [Equal.symbol](that: any): boolean { return ( failureIsInterrupt(that) && - Equal.equals(this.fiberId, that.fiberId) && - Equal.equals(this.annotations, that.annotations) + this.fiberId === that.fiberId && + this.annotations === that.annotations ) } [Hash.symbol](): number { - return Hash.cached(this, () => - Hash.combine(Hash.string(this._tag))( - Hash.combine(Hash.hash(this.fiberId))(Hash.hash(this.annotations)) - )) + return Hash.combine(Hash.string(`${this._tag}:${this.fiberId}`))( + Hash.random(this.annotations) + ) } } @@ -226,7 +225,7 @@ export const causeMerge: { const newCause = new CauseImpl( Arr.union(self.failures, that.failures) ) - return self[Equal.symbol](newCause) ? self : newCause + return Equal.equals(self, newCause) ? self : newCause } ) diff --git a/packages/effect/src/internal/equal.ts b/packages/effect/src/internal/equal.ts new file mode 100644 index 0000000000..99e2e7b73c --- /dev/null +++ b/packages/effect/src/internal/equal.ts @@ -0,0 +1,50 @@ +/** @internal */ +export const getAllObjectKeys = (obj: object): Set => { + const keys = new Set() + let current = obj + + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current) + for (const key of ownKeys) { + // Skip constructor property only when it's the default constructor reference + // Include it when it's a user-defined property with a different value + if (key === "constructor") { + const descriptor = Object.getOwnPropertyDescriptor(current, key) + if (descriptor) { + if (current === obj) { + // For the object itself, include constructor if it has been explicitly set to a different value + // Skip it if it's the default constructor reference + const proto = Object.getPrototypeOf(obj) + const expectedConstructor = proto?.constructor + if (descriptor.value !== expectedConstructor) { + keys.add(key) + } + } else { + // For prototype chain, include constructor if it's a meaningful user-defined value + // Skip it only if it's the natural constructor for this prototype + // (i.e., the constructor property points to the function AND that function's prototype is this object) + const isNaturalConstructor = typeof descriptor.value === "function" && + descriptor.value.prototype === current + if (!isNaturalConstructor) { + keys.add(key) + } + } + } + continue + } + + keys.add(key) + } + + if (obj instanceof Error) { + keys.delete("stack") + } + + current = Object.getPrototypeOf(current) + } + + return keys +} + +/** @internal */ +export const byReferenceInstances = new WeakSet() diff --git a/packages/effect/src/internal/hashSet.ts b/packages/effect/src/internal/hashSet.ts index 181280924c..4f9417dfa0 100644 --- a/packages/effect/src/internal/hashSet.ts +++ b/packages/effect/src/internal/hashSet.ts @@ -24,7 +24,7 @@ export interface HashSet extends Iterable, Equal.Equal, Pipeable, Insp const HashSetProto: Omit, HashSetTypeId> = { [Hash.symbol](this: HashSet): number { - return Hash.cached(this, () => Hash.hash(HashSetTypeId)) + return Hash.hash(HashSetTypeId) }, [Equal.symbol](this: HashSet, that: unknown): boolean { return isHashSet(that) && size(this) === size(that) && every(this, (value) => has(that, value)) diff --git a/packages/effect/src/internal/option.ts b/packages/effect/src/internal/option.ts index f43dc16dfc..1d2f21c365 100644 --- a/packages/effect/src/internal/option.ts +++ b/packages/effect/src/internal/option.ts @@ -27,7 +27,7 @@ const SomeProto = Object.assign(Object.create(CommonProto), { ) }, [Hash.symbol](this: Option.Some) { - return Hash.cached(this, () => Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value))) + return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value)) }, toString(this: Option.Some) { return `some(${format(this.value)})` diff --git a/packages/effect/src/internal/trie.ts b/packages/effect/src/internal/trie.ts index 6c93cccfd8..bfd9d8afa4 100644 --- a/packages/effect/src/internal/trie.ts +++ b/packages/effect/src/internal/trie.ts @@ -33,13 +33,11 @@ const TrieProto: TR.Trie = { return new TrieIterator(this, (k, v) => [k, v], () => true) }, [Hash.symbol](this: TR.Trie): number { - return Hash.cached(this, () => { - let hash = Hash.hash(TrieTypeId) - for (const item of this) { - hash ^= pipe(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1]))) - } - return hash - }) + let hash = Hash.hash(TrieTypeId) + for (const item of this) { + hash ^= pipe(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1]))) + } + return hash }, [Equal.symbol](this: TrieImpl, that: unknown): boolean { if (isTrie(that)) { diff --git a/packages/effect/src/platform/FileSystem.ts b/packages/effect/src/platform/FileSystem.ts index 3eb54b462b..59f27bbf3a 100644 --- a/packages/effect/src/platform/FileSystem.ts +++ b/packages/effect/src/platform/FileSystem.ts @@ -39,7 +39,6 @@ */ import * as Arr from "../collections/Array.ts" import * as Brand from "../data/Brand.ts" -import * as Data from "../data/Data.ts" import * as UndefinedOr from "../data/UndefinedOr.ts" import * as Effect from "../Effect.ts" import { pipe } from "../Function.ts" @@ -1226,36 +1225,6 @@ export declare namespace WatchEvent { } } -/** - * Creates a file creation watch event. - * - * @since 4.0.0 - * @category constructor - */ -export const WatchEventCreate: Data.Case.Constructor = Data.tagged( - "Create" -) - -/** - * Creates a file update watch event. - * - * @since 4.0.0 - * @category constructor - */ -export const WatchEventUpdate: Data.Case.Constructor = Data.tagged( - "Update" -) - -/** - * Creates a file removal watch event. - * - * @since 4.0.0 - * @category constructor - */ -export const WatchEventRemove: Data.Case.Constructor = Data.tagged( - "Remove" -) - /** * Service key for file system watch backend implementations. * diff --git a/packages/effect/src/primitives/BigDecimal.ts b/packages/effect/src/primitives/BigDecimal.ts index 9eee4e1c07..04f5a19b1d 100644 --- a/packages/effect/src/primitives/BigDecimal.ts +++ b/packages/effect/src/primitives/BigDecimal.ts @@ -56,10 +56,8 @@ export interface BigDecimal extends Equal.Equal, Pipeable, Inspectable { const BigDecimalProto: Omit = { [TypeId]: TypeId, [Hash.symbol](this: BigDecimal): number { - return Hash.cached(this, () => { - const normalized = normalize(this) - return Hash.combine(Hash.hash(normalized.value), Hash.number(normalized.scale)) - }) + const normalized = normalize(this) + return Hash.combine(Hash.hash(normalized.value), Hash.number(normalized.scale)) }, [Equal.symbol](this: BigDecimal, that: unknown): boolean { return isBigDecimal(that) && equals(this, that) diff --git a/packages/effect/src/time/Cron.ts b/packages/effect/src/time/Cron.ts index 0525b09d5f..c1b8a1d69b 100644 --- a/packages/effect/src/time/Cron.ts +++ b/packages/effect/src/time/Cron.ts @@ -95,16 +95,15 @@ const CronProto = { return isCron(that) && equals(this, that) }, [Hash.symbol](this: Cron): number { - return Hash.cached(this, () => - pipe( - Hash.hash(this.tz), - Hash.combine(Hash.array(Arr.fromIterable(this.seconds))), - Hash.combine(Hash.array(Arr.fromIterable(this.minutes))), - Hash.combine(Hash.array(Arr.fromIterable(this.hours))), - Hash.combine(Hash.array(Arr.fromIterable(this.days))), - Hash.combine(Hash.array(Arr.fromIterable(this.months))), - Hash.combine(Hash.array(Arr.fromIterable(this.weekdays))) - )) + return pipe( + Hash.hash(this.tz), + Hash.combine(Hash.array(Arr.fromIterable(this.seconds))), + Hash.combine(Hash.array(Arr.fromIterable(this.minutes))), + Hash.combine(Hash.array(Arr.fromIterable(this.hours))), + Hash.combine(Hash.array(Arr.fromIterable(this.days))), + Hash.combine(Hash.array(Arr.fromIterable(this.months))), + Hash.combine(Hash.array(Arr.fromIterable(this.weekdays))) + ) }, toObject(this: Cron) { return { diff --git a/packages/effect/src/time/Duration.ts b/packages/effect/src/time/Duration.ts index 7fa850d4a7..84fdba1704 100644 --- a/packages/effect/src/time/Duration.ts +++ b/packages/effect/src/time/Duration.ts @@ -193,7 +193,7 @@ const infinityDurationValue: DurationValue = { _tag: "Infinity" } const DurationProto: Omit = { [TypeId]: TypeId, [Hash.symbol](this: Duration) { - return Hash.cached(this, () => Hash.structure(this.value)) + return Hash.structure(this.value) }, [Equal.symbol](this: Duration, that: unknown): boolean { return isDuration(that) && equals(this, that) diff --git a/packages/effect/src/unstable/cluster/EntityAddress.ts b/packages/effect/src/unstable/cluster/EntityAddress.ts index f1dd7fef31..313216d1d3 100644 --- a/packages/effect/src/unstable/cluster/EntityAddress.ts +++ b/packages/effect/src/unstable/cluster/EntityAddress.ts @@ -31,14 +31,14 @@ export class EntityAddress extends Schema.Class(TypeId)({ */ [Equal.symbol](that: EntityAddress): boolean { return this.entityType === that.entityType && this.entityId === that.entityId && - this.shardId[Equal.symbol](that.shardId) + Equal.equals(this.shardId, that.shardId) } /** * @since 4.0.0 */ [Hash.symbol]() { - return Hash.cached(this, () => Hash.string(`${this.entityType}:${this.entityId}:${this.shardId.toString()}`)) + return Hash.string(`${this.entityType}:${this.entityId}:${this.shardId.toString()}`) } } /** diff --git a/packages/effect/src/unstable/cluster/Runner.ts b/packages/effect/src/unstable/cluster/Runner.ts index 8ffe09db2a..01f2932c6e 100644 --- a/packages/effect/src/unstable/cluster/Runner.ts +++ b/packages/effect/src/unstable/cluster/Runner.ts @@ -59,14 +59,14 @@ export class Runner extends Schema.Class(TypeId)({ * @since 4.0.0 */ [Equal.symbol](that: Runner): boolean { - return this.address[Equal.symbol](that.address) && this.version === that.version + return Equal.equals(this.address, that.address) && this.version === that.version } /** * @since 4.0.0 */ [Hash.symbol](): number { - return Hash.cached(this, () => Hash.string(`${this.address.toString()}:${this.version}`)) + return Hash.string(`${this.address.toString()}:${this.version}`) } } diff --git a/packages/effect/src/unstable/cluster/RunnerAddress.ts b/packages/effect/src/unstable/cluster/RunnerAddress.ts index dbdd0399fa..dfff167d0b 100644 --- a/packages/effect/src/unstable/cluster/RunnerAddress.ts +++ b/packages/effect/src/unstable/cluster/RunnerAddress.ts @@ -32,7 +32,7 @@ export class RunnerAddress extends Schema.Class(TypeId)({ * @since 4.0.0 */ [Hash.symbol]() { - return Hash.cached(this, () => Hash.string(this.toString())) + return Hash.string(this.toString()) } /** diff --git a/packages/effect/src/unstable/cluster/ShardId.ts b/packages/effect/src/unstable/cluster/ShardId.ts index a200c0b2d3..ee634b34bf 100644 --- a/packages/effect/src/unstable/cluster/ShardId.ts +++ b/packages/effect/src/unstable/cluster/ShardId.ts @@ -39,7 +39,7 @@ export class ShardId extends S.Class(TypeId)({ * @since 4.0.0 */ [Hash.symbol](): number { - return Hash.cached(this, () => Hash.string(this.toString())) + return Hash.string(this.toString()) } /** diff --git a/packages/effect/src/unstable/cluster/Sharding.ts b/packages/effect/src/unstable/cluster/Sharding.ts index 047ce63c9f..62a68a1f9b 100644 --- a/packages/effect/src/unstable/cluster/Sharding.ts +++ b/packages/effect/src/unstable/cluster/Sharding.ts @@ -284,7 +284,7 @@ const make = Effect.gen(function*() { ).pipe( Effect.flatMap((acquired) => { for (const shardId of acquiredShards) { - if (!acquired.some((_) => _[Equal.symbol](shardId))) { + if (!acquired.some((_) => Equal.equals(_, shardId))) { MutableHashSet.remove(acquiredShards, shardId) MutableHashSet.add(releasingShards, shardId) } diff --git a/packages/effect/src/unstable/cluster/SingletonAddress.ts b/packages/effect/src/unstable/cluster/SingletonAddress.ts index bdb236d0df..fe1ee10d3a 100644 --- a/packages/effect/src/unstable/cluster/SingletonAddress.ts +++ b/packages/effect/src/unstable/cluster/SingletonAddress.ts @@ -26,12 +26,12 @@ export class SingletonAddress extends Schema.Class(TypeId)({ * @since 4.0.0 */ [Hash.symbol]() { - return Hash.cached(this, () => Hash.string(`${this.name}:${this.shardId.toString()}`)) + return Hash.string(`${this.name}:${this.shardId.toString()}`) } /** * @since 4.0.0 */ [Equal.symbol](that: SingletonAddress): boolean { - return this.name === that.name && this.shardId[Equal.symbol](that.shardId) + return this.name === that.name && Equal.equals(this.shardId, that.shardId) } } diff --git a/packages/effect/src/unstable/cluster/internal/entityManager.ts b/packages/effect/src/unstable/cluster/internal/entityManager.ts index 1fad352e97..7df89300f8 100644 --- a/packages/effect/src/unstable/cluster/internal/entityManager.ts +++ b/packages/effect/src/unstable/cluster/internal/entityManager.ts @@ -414,7 +414,7 @@ export const make = Effect.fnUntraced(function*< Effect.suspend(function loop(): Effect.Effect { const toInterrupt = new Set() for (const state of activeServers.values()) { - if (shardId[Equal.symbol](state.address.shardId)) { + if (Equal.equals(shardId, state.address.shardId)) { toInterrupt.add(state) } } diff --git a/packages/effect/src/unstable/http/Headers.ts b/packages/effect/src/unstable/http/Headers.ts index f85aa16f1c..884c96ab88 100644 --- a/packages/effect/src/unstable/http/Headers.ts +++ b/packages/effect/src/unstable/http/Headers.ts @@ -55,7 +55,7 @@ const Proto = Object.assign(Object.create(null), { return Equivalence(this, that) }, [Hash.symbol](this: Headers): number { - return Hash.cached(this, () => Hash.structure(this)) + return Hash.structure(this) } }) diff --git a/packages/effect/src/unstable/http/UrlParams.ts b/packages/effect/src/unstable/http/UrlParams.ts index d23f5165f9..86a9ccdcc4 100644 --- a/packages/effect/src/unstable/http/UrlParams.ts +++ b/packages/effect/src/unstable/http/UrlParams.ts @@ -79,7 +79,7 @@ const Proto = { return Equivalence(this, that) }, [Hash.symbol](this: UrlParams): number { - return Hash.cached(this, () => Hash.array(this.params.flat())) + return Hash.array(this.params.flat()) } } diff --git a/packages/effect/src/unstable/sql/SqlResolver.ts b/packages/effect/src/unstable/sql/SqlResolver.ts index 3701ccd952..b9595f0831 100644 --- a/packages/effect/src/unstable/sql/SqlResolver.ts +++ b/packages/effect/src/unstable/sql/SqlResolver.ts @@ -32,7 +32,7 @@ const SqlRequestProto = { return Equal.equals(this.payload, that.payload) }, [Hash.symbol](this: SqlRequest): number { - return Hash.cached(this, () => Hash.hash(this.payload)) + return Hash.hash(this.payload) } } diff --git a/packages/effect/test/Equal.test.ts b/packages/effect/test/Equal.test.ts new file mode 100644 index 0000000000..73602a1e15 --- /dev/null +++ b/packages/effect/test/Equal.test.ts @@ -0,0 +1,1270 @@ +import * as HashMap from "effect/collections/HashMap" +import * as Option from "effect/data/Option" +import * as Equal from "effect/interfaces/Equal" +import * as Hash from "effect/interfaces/Hash" +import { describe, expect, it } from "vitest" + +describe("Equal - Structural Equality Behavior", () => { + describe("plain objects", () => { + it("should return true for structurally identical objects (structural equality)", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return true for same reference", () => { + const obj = { a: 1, b: 2 } + expect(Equal.equals(obj, obj)).toBe(true) + }) + + it("should return true for empty objects", () => { + expect(Equal.equals({}, {})).toBe(true) + }) + + it("should return false for objects with different values", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 3 } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should return false for objects with different keys", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, c: 2 } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + describe("symbol properties", () => { + it("should return true for objects with identical symbol keys and values", () => { + const sym1 = Symbol("test") + const sym2 = Symbol("other") + const obj1 = { [sym1]: 1, [sym2]: 2 } + const obj2 = { [sym1]: 1, [sym2]: 2 } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return false for objects with different symbol keys", () => { + const sym1 = Symbol("test") + const sym2 = Symbol("test") // Different symbol with same description + const obj1 = { [sym1]: 1 } + const obj2 = { [sym2]: 1 } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should return false for objects with different symbol values", () => { + const sym = Symbol("test") + const obj1 = { [sym]: 1 } + const obj2 = { [sym]: 2 } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should return true for objects with mixed string and symbol keys", () => { + const sym = Symbol("test") + const obj1 = { a: 1, [sym]: 2 } + const obj2 = { a: 1, [sym]: 2 } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return false when one object has symbol keys and the other doesn't", () => { + const sym = Symbol("test") + const obj1 = { a: 1, [sym]: 2 } + const obj2 = { a: 1 } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should consider non-enumerable symbol properties", () => { + const sym1 = Symbol("enumerable") + const sym2 = Symbol("non-enumerable") + const obj1: any = { a: 1 } + const obj2: any = { a: 1 } + + // Add enumerable symbol property + obj1[sym1] = "visible" + obj2[sym1] = "visible" + + // Add non-enumerable symbol property with same value + Object.defineProperty(obj1, sym2, { value: "hidden", enumerable: false }) + Object.defineProperty(obj2, sym2, { value: "hidden", enumerable: false }) + + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should consider non-enumerable symbol properties even when they differ", () => { + const sym1 = Symbol("enumerable") + const sym2 = Symbol("non-enumerable") + const obj1: any = { a: 1 } + const obj2: any = { a: 1 } + + // Add same enumerable symbol property + obj1[sym1] = "visible" + obj2[sym1] = "visible" + + // Add non-enumerable symbol properties with different values + Object.defineProperty(obj1, sym2, { value: "hidden1", enumerable: false }) + Object.defineProperty(obj2, sym2, { value: "hidden2", enumerable: false }) + + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should consider enumerable symbol properties even when string properties are the same", () => { + const sym = Symbol("test") + const obj1: any = { a: 1, b: 2 } + const obj2: any = { a: 1, b: 2 } + + obj1[sym] = "different" + obj2[sym] = "values" + + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) + + describe("non-enumerable properties", () => { + it("should handle non-enumerable string properties correctly", () => { + const obj1 = { a: 1 } + const obj2 = { a: 1 } + + Object.defineProperty(obj1, "hidden", { value: "secret", enumerable: false }) + Object.defineProperty(obj2, "hidden", { value: "secret", enumerable: false }) + + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should consider non-enumerable string properties even when they differ", () => { + const obj1 = { a: 1 } + const obj2 = { a: 1 } + + Object.defineProperty(obj1, "hidden", { value: "secret1", enumerable: false }) + Object.defineProperty(obj2, "hidden", { value: "secret2", enumerable: false }) + + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should consider enumerable properties and non-enumerable ones", () => { + const obj1: any = { a: 1 } + const obj2: any = { a: 1 } + + // Add same enumerable property + obj1.b = 2 + obj2.b = 2 + + // Add different non-enumerable properties (should be considered) + Object.defineProperty(obj1, "hidden", { value: "secret1", enumerable: false }) + Object.defineProperty(obj2, "hidden", { value: "secret2", enumerable: false }) + + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) + + describe("hash consistency with symbol properties", () => { + it("should produce same hash for objects with identical symbol keys and values", () => { + const sym1 = Symbol("test") + const sym2 = Symbol("other") + const obj1 = { [sym1]: 1, [sym2]: 2 } + const obj2 = { [sym1]: 1, [sym2]: 2 } + + expect(Hash.hash(obj1)).toBe(Hash.hash(obj2)) + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return false for equality even if symbols have same hash", () => { + const sym1 = Symbol("test") + const sym2 = Symbol("test") // Different symbol with same description + const obj1 = { [sym1]: 1 } + const obj2 = { [sym2]: 1 } + + // Note: symbols with same description may have same hash (acceptable hash collision) + // but equality should still work correctly + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should produce different hash for symbols with different descriptions", () => { + const sym1 = Symbol("first") + const sym2 = Symbol("second") + const obj1 = { [sym1]: 1 } + const obj2 = { [sym2]: 1 } + + expect(Hash.hash(obj1)).not.toBe(Hash.hash(obj2)) + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should produce different hash for objects with different symbol values", () => { + const sym = Symbol("test") + const obj1 = { [sym]: 1 } + const obj2 = { [sym]: 2 } + + expect(Hash.hash(obj1)).not.toBe(Hash.hash(obj2)) + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should produce same hash for objects with mixed string and symbol keys", () => { + const sym = Symbol("test") + const obj1 = { a: 1, [sym]: 2 } + const obj2 = { a: 1, [sym]: 2 } + + expect(Hash.hash(obj1)).toBe(Hash.hash(obj2)) + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should consider non-enumerable symbol properties in hash calculation", () => { + const sym1 = Symbol("enumerable") + const sym2 = Symbol("non-enumerable") + const obj1: any = { a: 1 } + const obj2: any = { a: 1 } + + // Add same enumerable symbol property + obj1[sym1] = "visible" + obj2[sym1] = "visible" + + // Add different non-enumerable symbol properties + Object.defineProperty(obj1, sym2, { value: "hidden1", enumerable: false }) + Object.defineProperty(obj2, sym2, { value: "hidden2", enumerable: false }) + + expect(Hash.hash(obj1)).not.toBe(Hash.hash(obj2)) + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) + }) + + describe("plain arrays", () => { + it("should return true for structurally identical arrays (structural equality)", () => { + const arr1 = [1, 2, 3] + const arr2 = [1, 2, 3] + expect(Equal.equals(arr1, arr2)).toBe(true) + }) + + it("should return true for same reference", () => { + const arr = [1, 2, 3] + expect(Equal.equals(arr, arr)).toBe(true) + }) + + it("should return true for empty arrays", () => { + expect(Equal.equals([], [])).toBe(true) + }) + + it("should return false for arrays with different elements", () => { + const arr1 = [1, 2, 3] + const arr2 = [1, 2, 4] + expect(Equal.equals(arr1, arr2)).toBe(false) + }) + + it("should return false for arrays with different lengths", () => { + const arr1 = [1, 2, 3] + const arr2 = [1, 2] + expect(Equal.equals(arr1, arr2)).toBe(false) + }) + }) + + describe("primitives", () => { + it("should work correctly for numbers", () => { + expect(Equal.equals(42, 42)).toBe(true) + expect(Equal.equals(42, 43)).toBe(false) + }) + + it("should work correctly for strings", () => { + expect(Equal.equals("hello", "hello")).toBe(true) + expect(Equal.equals("hello", "world")).toBe(false) + }) + + it("should work correctly for booleans", () => { + expect(Equal.equals(true, true)).toBe(true) + expect(Equal.equals(false, false)).toBe(true) + expect(Equal.equals(true, false)).toBe(false) + }) + + it("should work correctly for null and undefined", () => { + expect(Equal.equals(null, null)).toBe(true) + expect(Equal.equals(undefined, undefined)).toBe(true) + expect(Equal.equals(null, undefined)).toBe(false) + }) + }) + + describe("Date objects", () => { + it("should compare dates by ISO string", () => { + const date1 = new Date("2023-01-01T00:00:00.000Z") + const date2 = new Date("2023-01-01T00:00:00.000Z") + expect(Equal.equals(date1, date2)).toBe(true) + }) + + it("should return false for different dates", () => { + const date1 = new Date("2023-01-01T00:00:00.000Z") + const date2 = new Date("2023-01-02T00:00:00.000Z") + expect(Equal.equals(date1, date2)).toBe(false) + }) + }) + + describe("Effect data structures", () => { + it("should work with HashMap (implements Equal interface)", () => { + const map1 = HashMap.make(["a", 1], ["b", 2]) + const map2 = HashMap.make(["a", 1], ["b", 2]) + expect(Equal.equals(map1, map2)).toBe(true) + }) + + it("should work with Option (implements Equal interface)", () => { + const opt1 = Option.some(42) + const opt2 = Option.some(42) + expect(Equal.equals(opt1, opt2)).toBe(true) + }) + + it("HashMap should not equal plain objects", () => { + const map = HashMap.make(["a", 1], ["b", 2]) + const obj = { a: 1, b: 2 } + expect(Equal.equals(map, obj)).toBe(false) + }) + }) + + describe("custom Equal implementations", () => { + class CustomPoint implements Equal.Equal { + constructor(readonly x: number, readonly y: number) {} + + [Equal.symbol](that: Equal.Equal): boolean { + return that instanceof CustomPoint && + this.x === that.x && + this.y === that.y + } + + [Hash.symbol](): number { + return 0 + } + } + + it("should work with custom Equal implementation", () => { + const point1 = new CustomPoint(1, 2) + const point2 = new CustomPoint(1, 2) + expect(Equal.equals(point1, point2)).toBe(true) + }) + }) + + describe("nested structures", () => { + it("should return true for nested objects (deep structural equality)", () => { + const obj1 = { a: { b: 1 }, c: [1, 2] } + const obj2 = { a: { b: 1 }, c: [1, 2] } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return true for nested arrays (deep structural equality)", () => { + const arr1 = [[1, 2], [3, 4]] + const arr2 = [[1, 2], [3, 4]] + expect(Equal.equals(arr1, arr2)).toBe(true) + }) + + it("should return false for nested objects with different values", () => { + const obj1 = { a: { b: 1 }, c: [1, 2] } + const obj2 = { a: { b: 2 }, c: [1, 2] } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should return false for nested arrays with different values", () => { + const arr1 = [[1, 2], [3, 4]] + const arr2 = [[1, 3], [3, 4]] + expect(Equal.equals(arr1, arr2)).toBe(false) + }) + }) + + describe("special values", () => { + describe("NaN", () => { + it("should handle NaN correctly (structural equality - NaN equals NaN)", () => { + expect(Equal.equals(NaN, NaN)).toBe(true) + }) + + it("should return false when comparing NaN with regular numbers", () => { + expect(Equal.equals(NaN, 0)).toBe(false) + expect(Equal.equals(NaN, 42)).toBe(false) + expect(Equal.equals(42, NaN)).toBe(false) + }) + + it("should return false when comparing NaN with Infinity", () => { + expect(Equal.equals(NaN, Infinity)).toBe(false) + expect(Equal.equals(NaN, -Infinity)).toBe(false) + expect(Equal.equals(Infinity, NaN)).toBe(false) + expect(Equal.equals(-Infinity, NaN)).toBe(false) + }) + + it("should handle NaN in arrays", () => { + expect(Equal.equals([NaN], [NaN])).toBe(true) + expect(Equal.equals([NaN, 1], [NaN, 1])).toBe(true) + expect(Equal.equals([NaN, 1], [NaN, 2])).toBe(false) + expect(Equal.equals([NaN], [Infinity])).toBe(false) + }) + + it("should handle NaN in objects", () => { + expect(Equal.equals({ a: NaN }, { a: NaN })).toBe(true) + expect(Equal.equals({ a: NaN, b: 1 }, { a: NaN, b: 1 })).toBe(true) + expect(Equal.equals({ a: NaN }, { a: Infinity })).toBe(false) + expect(Equal.equals({ a: NaN }, { a: 42 })).toBe(false) + }) + + it("should handle NaN in nested structures", () => { + expect(Equal.equals({ arr: [NaN] }, { arr: [NaN] })).toBe(true) + expect(Equal.equals([{ val: NaN }], [{ val: NaN }])).toBe(true) + expect(Equal.equals({ nested: { deep: NaN } }, { nested: { deep: NaN } })).toBe(true) + expect(Equal.equals({ arr: [NaN] }, { arr: [Infinity] })).toBe(false) + }) + }) + + describe("Infinity", () => { + it("should handle Infinity correctly (structural equality)", () => { + expect(Equal.equals(Infinity, Infinity)).toBe(true) + }) + + it("should return false when comparing Infinity with regular numbers", () => { + expect(Equal.equals(Infinity, 0)).toBe(false) + expect(Equal.equals(Infinity, 42)).toBe(false) + expect(Equal.equals(42, Infinity)).toBe(false) + expect(Equal.equals(Infinity, Number.MAX_VALUE)).toBe(false) + }) + + it("should return false when comparing Infinity with -Infinity", () => { + expect(Equal.equals(Infinity, -Infinity)).toBe(false) + expect(Equal.equals(-Infinity, Infinity)).toBe(false) + }) + + it("should handle Infinity in arrays", () => { + expect(Equal.equals([Infinity], [Infinity])).toBe(true) + expect(Equal.equals([Infinity, 1], [Infinity, 1])).toBe(true) + expect(Equal.equals([Infinity, 1], [Infinity, 2])).toBe(false) + expect(Equal.equals([Infinity], [-Infinity])).toBe(false) + }) + + it("should handle Infinity in objects", () => { + expect(Equal.equals({ a: Infinity }, { a: Infinity })).toBe(true) + expect(Equal.equals({ a: Infinity, b: 1 }, { a: Infinity, b: 1 })).toBe(true) + expect(Equal.equals({ a: Infinity }, { a: -Infinity })).toBe(false) + expect(Equal.equals({ a: Infinity }, { a: 42 })).toBe(false) + }) + + it("should handle Infinity in nested structures", () => { + expect(Equal.equals({ arr: [Infinity] }, { arr: [Infinity] })).toBe(true) + expect(Equal.equals([{ val: Infinity }], [{ val: Infinity }])).toBe(true) + expect(Equal.equals({ nested: { deep: Infinity } }, { nested: { deep: Infinity } })).toBe(true) + expect(Equal.equals({ arr: [Infinity] }, { arr: [-Infinity] })).toBe(false) + }) + }) + + describe("-Infinity", () => { + it("should handle -Infinity correctly (structural equality)", () => { + expect(Equal.equals(-Infinity, -Infinity)).toBe(true) + }) + + it("should return false when comparing -Infinity with regular numbers", () => { + expect(Equal.equals(-Infinity, 0)).toBe(false) + expect(Equal.equals(-Infinity, -42)).toBe(false) + expect(Equal.equals(-42, -Infinity)).toBe(false) + expect(Equal.equals(-Infinity, Number.MIN_VALUE)).toBe(false) + }) + + it("should handle -Infinity in arrays", () => { + expect(Equal.equals([-Infinity], [-Infinity])).toBe(true) + expect(Equal.equals([-Infinity, 1], [-Infinity, 1])).toBe(true) + expect(Equal.equals([-Infinity, 1], [-Infinity, 2])).toBe(false) + expect(Equal.equals([-Infinity], [Infinity])).toBe(false) + }) + + it("should handle -Infinity in objects", () => { + expect(Equal.equals({ a: -Infinity }, { a: -Infinity })).toBe(true) + expect(Equal.equals({ a: -Infinity, b: 1 }, { a: -Infinity, b: 1 })).toBe(true) + expect(Equal.equals({ a: -Infinity }, { a: Infinity })).toBe(false) + expect(Equal.equals({ a: -Infinity }, { a: -42 })).toBe(false) + }) + + it("should handle -Infinity in nested structures", () => { + expect(Equal.equals({ arr: [-Infinity] }, { arr: [-Infinity] })).toBe(true) + expect(Equal.equals([{ val: -Infinity }], [{ val: -Infinity }])).toBe(true) + expect(Equal.equals({ nested: { deep: -Infinity } }, { nested: { deep: -Infinity } })).toBe(true) + expect(Equal.equals({ arr: [-Infinity] }, { arr: [Infinity] })).toBe(false) + }) + }) + + describe("mixed special values", () => { + it("should handle arrays with multiple special values", () => { + expect(Equal.equals([NaN, Infinity, -Infinity], [NaN, Infinity, -Infinity])).toBe(true) + expect(Equal.equals([NaN, Infinity], [Infinity, NaN])).toBe(false) // order matters + expect(Equal.equals([NaN, Infinity, 0], [NaN, Infinity, 0])).toBe(true) + }) + + it("should handle objects with multiple special values", () => { + expect(Equal.equals( + { nan: NaN, inf: Infinity, negInf: -Infinity }, + { nan: NaN, inf: Infinity, negInf: -Infinity } + )).toBe(true) + expect(Equal.equals( + { nan: NaN, inf: Infinity }, + { nan: NaN, inf: -Infinity } + )).toBe(false) + }) + + it("should handle complex nested structures with special values", () => { + const obj1 = { + data: [ + { value: NaN, meta: { type: "special" } }, + { value: Infinity, meta: { type: "infinite" } }, + { value: -Infinity, meta: { type: "negative-infinite" } } + ] + } + const obj2 = { + data: [ + { value: NaN, meta: { type: "special" } }, + { value: Infinity, meta: { type: "infinite" } }, + { value: -Infinity, meta: { type: "negative-infinite" } } + ] + } + const obj3 = { + data: [ + { value: NaN, meta: { type: "special" } }, + { value: -Infinity, meta: { type: "infinite" } }, // swapped values + { value: Infinity, meta: { type: "negative-infinite" } } + ] + } + + expect(Equal.equals(obj1, obj2)).toBe(true) + expect(Equal.equals(obj1, obj3)).toBe(false) + }) + }) + + describe("zero values", () => { + it("should handle -0 and +0 correctly", () => { + expect(Equal.equals(-0, +0)).toBe(true) + expect(Equal.equals(0, -0)).toBe(true) + expect(Equal.equals(+0, -0)).toBe(true) + }) + + it("should handle zero values in arrays", () => { + expect(Equal.equals([-0], [+0])).toBe(true) + expect(Equal.equals([0], [-0])).toBe(true) + expect(Equal.equals([-0, 1], [+0, 1])).toBe(true) + }) + + it("should handle zero values in objects", () => { + expect(Equal.equals({ a: -0 }, { a: +0 })).toBe(true) + expect(Equal.equals({ a: 0 }, { a: -0 })).toBe(true) + }) + }) + }) + + describe("JavaScript Map", () => { + it("should return true for structurally identical maps", () => { + const map1 = new Map([["a", 1], ["b", 2]]) + const map2 = new Map([["a", 1], ["b", 2]]) + expect(Equal.equals(map1, map2)).toBe(true) + }) + + it("should return true for same reference", () => { + const map = new Map([["a", 1]]) + expect(Equal.equals(map, map)).toBe(true) + }) + + it("should return true for empty maps", () => { + expect(Equal.equals(new Map(), new Map())).toBe(true) + }) + + it("should return false for maps with different values", () => { + const map1 = new Map([["a", 1], ["b", 2]]) + const map2 = new Map([["a", 1], ["b", 3]]) + expect(Equal.equals(map1, map2)).toBe(false) + }) + + it("should return false for maps with different keys", () => { + const map1 = new Map([["a", 1], ["b", 2]]) + const map2 = new Map([["a", 1], ["c", 2]]) + expect(Equal.equals(map1, map2)).toBe(false) + }) + + it("should return false for maps with different sizes", () => { + const map1 = new Map([["a", 1], ["b", 2]]) + const map2 = new Map([["a", 1]]) + expect(Equal.equals(map1, map2)).toBe(false) + }) + + it("should handle maps with object keys", () => { + const key1 = { id: 1 } + const key2 = { id: 1 } + const map1 = new Map() + map1.set(key1, "value1") + map1.set({ nested: { x: 1 } }, "value2") + + const map2 = new Map() + map2.set(key2, "value1") + map2.set({ nested: { x: 1 } }, "value2") + + expect(Equal.equals(map1, map2)).toBe(true) + }) + + it("should handle maps with object values", () => { + const map1 = new Map([["a", { x: 1 }], ["b", { y: [1, 2] }]]) + const map2 = new Map([["a", { x: 1 }], ["b", { y: [1, 2] }]]) + expect(Equal.equals(map1, map2)).toBe(true) + }) + + it("should handle nested maps", () => { + const inner1 = new Map([["x", 1]]) + const inner2 = new Map([["x", 1]]) + const map1 = new Map([["nested", inner1]]) + const map2 = new Map([["nested", inner2]]) + expect(Equal.equals(map1, map2)).toBe(true) + }) + + it("should handle maps with special values", () => { + const map1 = new Map([[NaN, "nan"], [Infinity, "inf"], [-Infinity, "neginf"]]) + const map2 = new Map([[NaN, "nan"], [Infinity, "inf"], [-Infinity, "neginf"]]) + expect(Equal.equals(map1, map2)).toBe(true) + }) + }) + + describe("JavaScript Set", () => { + it("should return true for structurally identical sets", () => { + const set1 = new Set([1, 2, 3]) + const set2 = new Set([1, 2, 3]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + + it("should return true for same reference", () => { + const set = new Set([1, 2, 3]) + expect(Equal.equals(set, set)).toBe(true) + }) + + it("should return true for empty sets", () => { + expect(Equal.equals(new Set(), new Set())).toBe(true) + }) + + it("should return false for sets with different elements", () => { + const set1 = new Set([1, 2, 3]) + const set2 = new Set([1, 2, 4]) + expect(Equal.equals(set1, set2)).toBe(false) + }) + + it("should return false for sets with different sizes", () => { + const set1 = new Set([1, 2, 3]) + const set2 = new Set([1, 2]) + expect(Equal.equals(set1, set2)).toBe(false) + }) + + it("should return true for sets with same elements in different insertion order", () => { + const set1 = new Set([1, 2, 3]) + const set2 = new Set([3, 1, 2]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + + it("should handle sets with object elements", () => { + const set1 = new Set([{ x: 1 }, { y: 2 }]) + const set2 = new Set([{ x: 1 }, { y: 2 }]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + + it("should handle nested sets", () => { + const inner1 = new Set([1, 2]) + const inner2 = new Set([1, 2]) + const set1 = new Set([inner1, "other"]) + const set2 = new Set([inner2, "other"]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + + it("should handle sets with special values", () => { + const set1 = new Set([NaN, Infinity, -Infinity]) + const set2 = new Set([NaN, Infinity, -Infinity]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + + it("should handle sets with array elements", () => { + const set1 = new Set([[1, 2], [3, 4]]) + const set2 = new Set([[1, 2], [3, 4]]) + expect(Equal.equals(set1, set2)).toBe(true) + }) + }) + + describe("Map and Set mixed", () => { + it("should handle objects containing maps and sets", () => { + const obj1 = { + map: new Map([["a", 1], ["b", 2]]), + set: new Set([1, 2, 3]), + array: [new Map([["x", 1]]), new Set([4, 5])] + } + const obj2 = { + map: new Map([["a", 1], ["b", 2]]), + set: new Set([1, 2, 3]), + array: [new Map([["x", 1]]), new Set([4, 5])] + } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return false when Map/Set differ in nested structures", () => { + const obj1 = { + map: new Map([["a", 1], ["b", 2]]), + set: new Set([1, 2, 3]) + } + const obj2 = { + map: new Map([["a", 1], ["b", 3]]), // different value + set: new Set([1, 2, 3]) + } + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) + + describe("byReference", () => { + it("should allow objects to opt out of structural equality", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Normal structural equality + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Create instance equality version of obj1 + const obj1Instance = Equal.byReference(obj1) + expect(Equal.equals(obj1Instance, obj2)).toBe(false) + expect(Equal.equals(obj1Instance, obj1Instance)).toBe(true) + }) + + it("should work with arrays", () => { + const arr1 = [1, 2, 3] + const arr2 = [1, 2, 3] + + // Normal structural equality + expect(Equal.equals(arr1, arr2)).toBe(true) + + // Create instance equality version of arr1 + const arr1Instance = Equal.byReference(arr1) + expect(Equal.equals(arr1Instance, arr2)).toBe(false) + expect(Equal.equals(arr1Instance, arr1Instance)).toBe(true) + }) + + it("should work with Maps", () => { + const map1 = new Map([["a", 1]]) + const map2 = new Map([["a", 1]]) + + // Normal structural equality + expect(Equal.equals(map1, map2)).toBe(true) + + // Create instance equality version of map1 + const map1Instance = Equal.byReference(map1) + expect(Equal.equals(map1Instance, map2)).toBe(false) + expect(Equal.equals(map1Instance, map1Instance)).toBe(true) + }) + + it("should work with Sets", () => { + const set1 = new Set([1, 2]) + const set2 = new Set([1, 2]) + + // Normal structural equality + expect(Equal.equals(set1, set2)).toBe(true) + + // Create instance equality version of set1 + const set1Instance = Equal.byReference(set1) + expect(Equal.equals(set1Instance, set2)).toBe(false) + expect(Equal.equals(set1Instance, set1Instance)).toBe(true) + }) + + it("should return a proxy that behaves like the original object", () => { + const obj = { a: 1 } + const result = Equal.byReference(obj) + + // The result should not be the same reference (it's a proxy) + expect(result).not.toBe(obj) + + // But it should behave the same way + expect(result.a).toBe(1) + + // And should support property access + expect(result.a).toBe(obj.a) + }) + + it("should work when either object is marked for instance equality", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Create instance equality version of obj2 + const obj2Instance = Equal.byReference(obj2) + expect(Equal.equals(obj1, obj2Instance)).toBe(false) + expect(Equal.equals(obj2Instance, obj1)).toBe(false) + }) + + it("should work with nested structures", () => { + const obj1 = { a: { b: 1 }, c: [1, 2] } + const obj2 = { a: { b: 1 }, c: [1, 2] } + + // Normal structural equality + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Create instance equality version of obj1 + const obj1Instance = Equal.byReference(obj1) + expect(Equal.equals(obj1Instance, obj2)).toBe(false) + }) + }) + + describe("byReferenceUnsafe", () => { + it("should allow objects to opt out of structural equality without proxy", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Mark obj1 for reference equality (modifies obj1 directly) + const obj1ByRef = Equal.byReferenceUnsafe(obj1) + expect(obj1ByRef).toBe(obj1) // Same object, no proxy created + expect(Equal.equals(obj1ByRef, obj2)).toBe(false) // uses reference equality + expect(Equal.equals(obj1ByRef, obj1ByRef)).toBe(true) // same reference + + // The original obj1 now uses reference equality + expect(Equal.equals(obj1, obj2)).toBe(false) // obj1 uses reference equality + }) + + it("should work with arrays", () => { + const arr1 = [1, 2, 3] + const arr2 = [1, 2, 3] + + // Mark arr1 for reference equality + const arr1ByRef = Equal.byReferenceUnsafe(arr1) + expect(arr1ByRef).toBe(arr1) // Same array, no proxy + expect(Equal.equals(arr1ByRef, arr2)).toBe(false) + expect(Equal.equals(arr1ByRef, arr1ByRef)).toBe(true) + }) + + it("should work with Maps", () => { + const map1 = new Map([["a", 1]]) + const map2 = new Map([["a", 1]]) + + // Mark map1 for reference equality + const map1ByRef = Equal.byReferenceUnsafe(map1) + expect(map1ByRef).toBe(map1) // Same map, no proxy + expect(Equal.equals(map1ByRef, map2)).toBe(false) + expect(Equal.equals(map1ByRef, map1ByRef)).toBe(true) + }) + + it("should work with Sets", () => { + const set1 = new Set([1, 2]) + const set2 = new Set([1, 2]) + + // Mark set1 for reference equality + const set1ByRef = Equal.byReferenceUnsafe(set1) + expect(set1ByRef).toBe(set1) // Same set, no proxy + expect(Equal.equals(set1ByRef, set2)).toBe(false) + expect(Equal.equals(set1ByRef, set1ByRef)).toBe(true) + }) + + it("should permanently change object equality behavior", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Mark obj1 for reference equality + Equal.byReferenceUnsafe(obj1) + + // Now obj1 permanently uses reference equality + expect(Equal.equals(obj1, obj2)).toBe(false) + expect(Equal.equals(obj1, obj1)).toBe(true) + }) + + it("should work when either object is marked for reference equality", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Mark obj2 for reference equality + Equal.byReferenceUnsafe(obj2) + expect(Equal.equals(obj1, obj2)).toBe(false) + expect(Equal.equals(obj2, obj1)).toBe(false) + }) + + it("should work with nested structures", () => { + const obj1 = { a: { b: 1 }, c: [1, 2] } + const obj2 = { a: { b: 1 }, c: [1, 2] } + + // Mark obj1 for reference equality + Equal.byReferenceUnsafe(obj1) + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) + + describe("Error objects", () => { + it("should return true for Error objects with same message and additional properties", () => { + const error1 = new Error("test message") + ;(error1 as any).code = "TEST_CODE" + ;(error1 as any).details = { info: "additional details" } + + const error2 = new Error("test message") + ;(error2 as any).code = "TEST_CODE" + ;(error2 as any).details = { info: "additional details" } + + // Error objects are now structurally comparable (stack is excluded) + expect(Equal.equals(error1, error2)).toBe(true) + }) + + it("should return false for Error objects with different messages", () => { + const error1 = new Error("message 1") + ;(error1 as any).code = "TEST_CODE" + + const error2 = new Error("message 2") + ;(error2 as any).code = "TEST_CODE" + + expect(Equal.equals(error1, error2)).toBe(false) + }) + + it("should work with custom Error classes", () => { + class CustomError extends Error { + readonly code: string + constructor(message: string, code: string) { + super(message) + this.name = "CustomError" + this.code = code + } + } + + const error1 = new CustomError("test", "CUSTOM") + const error2 = new CustomError("test", "CUSTOM") + + // Custom Error objects are now structurally comparable (stack is excluded) + expect(Equal.equals(error1, error2)).toBe(true) + }) + + it("should ignore stack traces when comparing Error objects", () => { + function createErrorAtDifferentLocation1() { + return new Error("same message") + } + + function createErrorAtDifferentLocation2() { + return new Error("same message") + } + + const error1 = createErrorAtDifferentLocation1() + const error2 = createErrorAtDifferentLocation2() + + // Even though stack traces are different, errors should be equal + expect(error1.stack).not.toBe(error2.stack) + expect(Equal.equals(error1, error2)).toBe(true) + }) + }) + + describe("objects with different constructors", () => { + it("should return true for objects with different constructors but same shape", () => { + class CustomClass { + readonly a: number + readonly b: number + constructor() { + this.a = 1 + this.b = 2 + } + } + + const plainObject = { a: 1, b: 2 } + const customObject = new CustomClass() + expect(Equal.equals(plainObject, customObject)).toBe(true) + }) + + it("should return true for objects with null prototype", () => { + const nullProtoObject: any = Object.create(null) + nullProtoObject.a = 1 + nullProtoObject.b = 2 + + const plainObject = { a: 1, b: 2 } + expect(Equal.equals(nullProtoObject, plainObject)).toBe(true) + }) + + it("should return true for objects with different function constructors", () => { + function Constructor1(this: any) { + this.a = 1 + this.b = 2 + } + + function Constructor2(this: any) { + this.a = 1 + this.b = 2 + } + + const obj1 = new (Constructor1 as any)() + const obj2 = new (Constructor2 as any)() + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should return false when properties differ regardless of constructor", () => { + class CustomClass1 { + readonly a: number + readonly b: number + constructor() { + this.a = 1 + this.b = 2 + } + } + + class CustomClass2 { + readonly a: number + readonly b: number + constructor() { + this.a = 1 + this.b = 3 // Different value + } + } + + const obj1 = new CustomClass1() + const obj2 = new CustomClass2() + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + + it("should handle mixed constructor types in nested structures", () => { + class CustomClass { + readonly inner: { x: number } + constructor() { + this.inner = { x: 1 } + } + } + + const obj1 = { data: new CustomClass() } + const obj2 = { data: { inner: { x: 1 } } } + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should include constructor property when it has a meaningful user-defined value", () => { + const obj1 = { constructor: 10, a: 1 } + const obj2 = { constructor: 10, a: 1 } + const obj3 = { constructor: 20, a: 1 } + + // Objects with same constructor value should be equal + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Objects with different constructor values should not be equal + expect(Equal.equals(obj1, obj3)).toBe(false) + expect(Equal.equals(obj2, obj3)).toBe(false) + }) + + it("should include constructor property when it has a meaningful user-defined value from a prototype", () => { + const obj1 = Object.setPrototypeOf({ a: 1 }, { constructor: 10 }) + const obj2 = Object.setPrototypeOf({ a: 1 }, { constructor: 10 }) + const obj3 = Object.setPrototypeOf({ a: 1 }, { constructor: 20 }) + + // Objects with same constructor value should be equal + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Objects with different constructor values should not be equal + expect(Equal.equals(obj1, obj3)).toBe(false) + expect(Equal.equals(obj2, obj3)).toBe(false) + }) + + it("should include constructor property when it has a meaningful user-defined value from a prototype when it is a function", () => { + const f = () => 10 + const g = () => 10 + const obj1 = Object.setPrototypeOf({ a: 1 }, { constructor: f }) + const obj2 = Object.setPrototypeOf({ a: 1 }, { constructor: f }) + const obj3 = Object.setPrototypeOf({ a: 1 }, { constructor: g }) + + // Objects with same constructor value should be equal + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Objects with different constructor values should not be equal + expect(Equal.equals(obj1, obj3)).toBe(false) + expect(Equal.equals(obj2, obj3)).toBe(false) + }) + + it("should still ignore default constructor property", () => { + const obj1 = { a: 1, b: 2 } + const obj2 = { a: 1, b: 2 } + + // Normal objects should still be equal (constructor property ignored when it's the default) + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Verify that obj1.constructor and obj2.constructor are the default Object constructor + expect(obj1.constructor).toBe(Object) + expect(obj2.constructor).toBe(Object) + }) + }) + + describe("recursive objects", () => { + it("should handle circular references in Equal implementations without infinite recursion", () => { + class CircularEqualTest implements Equal.Equal { + constructor(readonly value: string, public child: CircularEqualTest | null = null) {} + + [Equal.symbol](that: Equal.Equal): boolean { + if (!(that instanceof CircularEqualTest)) { + return false + } + + // Circular references are handled automatically by the system + // This implementation can safely call Equal.equals without manual tracking + return this.value === that.value && Equal.equals(this.child, that.child) + } + + [Hash.symbol](): number { + return Hash.string(this.value) + } + } + + // Test case 1: Self-referencing objects + const obj1 = new CircularEqualTest("test") + obj1.child = obj1 + + const obj2 = new CircularEqualTest("test") + obj2.child = obj2 + + // This should not cause infinite recursion + expect(Equal.equals(obj1, obj2)).toBe(true) + + // Test case 2: Different values should not be equal even with same structure + const obj3 = new CircularEqualTest("different") + obj3.child = obj3 + + expect(Equal.equals(obj1, obj3)).toBe(false) + }) + + it("should handle complex circular references in Equal implementations", () => { + class ComplexEqualTest implements Equal.Equal { + constructor(readonly id: number, public ref: ComplexEqualTest | null = null) {} + + [Equal.symbol](that: Equal.Equal): boolean { + if (!(that instanceof ComplexEqualTest)) { + return false + } + + // Circular references are handled automatically by the system + return this.id === that.id && Equal.equals(this.ref, that.ref) + } + + [Hash.symbol](): number { + return Hash.number(this.id) + } + } + + // Create cycle: obj1 -> obj2 -> obj1 + const obj1 = new ComplexEqualTest(1) + const obj2 = new ComplexEqualTest(2) + obj1.ref = obj2 + obj2.ref = obj1 + + // Create identical cycle: obj3 -> obj4 -> obj3 + const obj3 = new ComplexEqualTest(1) + const obj4 = new ComplexEqualTest(2) + obj3.ref = obj4 + obj4.ref = obj3 + + // Should not cause infinite recursion and should be equal + expect(Equal.equals(obj1, obj3)).toBe(true) + expect(Equal.equals(obj2, obj4)).toBe(true) + }) + + it("should expose visited sets for advanced use cases", () => { + // Most implementations don't need manual tracking, but the sets are exposed + // for advanced scenarios where integration with the tracking system is needed + + class SimpleContainer implements Equal.Equal { + constructor(readonly name: string, readonly items: Array = []) {} + + [Equal.symbol](that: Equal.Equal): boolean { + if (!(that instanceof SimpleContainer)) { + return false + } + + // Simple implementation - no manual tracking needed + // Circular references are handled automatically + return this.name === that.name && + this.items.length === that.items.length && + this.items.every((item, i) => Equal.equals(item, that.items[i])) + } + + [Hash.symbol](): number { + // Simple hash implementation - circular references are handled automatically + let result = Hash.string(this.name) + for (const item of this.items) { + result = Hash.combine(result, Hash.hash(item)) + } + return result + } + } + + // Test that automatic circular reference handling works + const container1 = new SimpleContainer("A") + container1.items.push(container1) // Self-reference + + const container2 = new SimpleContainer("A") + container2.items.push(container2) // Self-reference + + // Should not cause infinite recursion due to automatic tracking + expect(Equal.equals(container1, container2)).toBe(true) + }) + + it("should handle objects with circular references without infinite recursion", () => { + // Create objects that reference themselves + const obj1: any = { a: 1, b: 2 } + obj1.self = obj1 + + const obj2: any = { a: 1, b: 2 } + obj2.self = obj2 + + // This should not throw due to stack overflow + expect(() => Equal.equals(obj1, obj2)).not.toThrow() + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should handle arrays with circular references without infinite recursion", () => { + // Create arrays that reference themselves + const arr1: any = [1, 2, 3] + arr1.push(arr1) + + const arr2: any = [1, 2, 3] + arr2.push(arr2) + + // This should not throw due to stack overflow + expect(() => Equal.equals(arr1, arr2)).not.toThrow() + expect(Equal.equals(arr1, arr2)).toBe(true) + }) + + it("should handle mixed circular references between objects and arrays", () => { + // Create complex circular structure + const obj1: any = { type: "object", items: [] } + const arr1: any = [1, 2, obj1] + obj1.items = arr1 + + const obj2: any = { type: "object", items: [] } + const arr2: any = [1, 2, obj2] + obj2.items = arr2 + + // This should not throw due to stack overflow + expect(() => Equal.equals(obj1, obj2)).not.toThrow() + expect(Equal.equals(obj1, obj2)).toBe(true) + }) + + it("should handle hashing objects with circular references without infinite recursion", () => { + // Create object that references itself + const obj: any = { a: 1, b: 2 } + obj.self = obj + + // This should not throw due to stack overflow + expect(() => Hash.hash(obj)).not.toThrow() + + // Hash should be consistent + const hash1 = Hash.hash(obj) + const hash2 = Hash.hash(obj) + expect(hash1).toBe(hash2) + }) + + it("should handle hashing arrays with circular references without infinite recursion", () => { + // Create array that references itself + const arr: any = [1, 2, 3] + arr.push(arr) + + // This should not throw due to stack overflow + expect(() => Hash.hash(arr)).not.toThrow() + + // Hash should be consistent + const hash1 = Hash.hash(arr) + const hash2 = Hash.hash(arr) + expect(hash1).toBe(hash2) + }) + + it("should produce different hashes for objects with different circular structures", () => { + const obj1: any = { a: 1, b: 2 } + obj1.self = obj1 + + const obj2: any = { a: 1, b: 3 } // Different value + obj2.self = obj2 + + // Should not throw and should produce different hashes + expect(() => Hash.hash(obj1)).not.toThrow() + expect(() => Hash.hash(obj2)).not.toThrow() + expect(Hash.hash(obj1)).not.toBe(Hash.hash(obj2)) + }) + + it("should return false for objects with different circular reference patterns", () => { + // Object that references itself + const obj1: any = { a: 1, b: 2 } + obj1.self = obj1 + + // Object that references a different object + const obj2: any = { a: 1, b: 2 } + const obj3: any = { a: 1, b: 2 } + obj2.self = obj3 + + // These should be considered different + expect(() => Equal.equals(obj1, obj2)).not.toThrow() + expect(Equal.equals(obj1, obj2)).toBe(false) + }) + }) +}) diff --git a/packages/effect/test/schema/ToEquivalence.test.ts b/packages/effect/test/schema/ToEquivalence.test.ts index 41c77f3d21..b1fe101e80 100644 --- a/packages/effect/test/schema/ToEquivalence.test.ts +++ b/packages/effect/test/schema/ToEquivalence.test.ts @@ -88,7 +88,7 @@ describe("ToEquivalence", () => { const equivalence = ToEquivalence.make(schema) const a = {} assertTrue(equivalence(a, a)) - assertFalse(equivalence({}, {})) + assertTrue(equivalence({}, {})) // Now supports structural equality }) it("required fields", () => { diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index 8138a89ab7..950ab3c404 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -536,13 +536,13 @@ const watchNode = (path: string) => switch (event) { case "rename": { Effect.runFork(Effect.matchEffect(stat(path), { - onSuccess: (_) => Queue.offer(queue, FileSystem.WatchEventCreate({ path })), - onFailure: (_) => Queue.offer(queue, FileSystem.WatchEventRemove({ path })) + onSuccess: (_) => Queue.offer(queue, { _tag: "Create", path }), + onFailure: (_) => Queue.offer(queue, { _tag: "Remove", path }) })) return } case "change": { - Queue.offerUnsafe(queue, FileSystem.WatchEventUpdate({ path })) + Queue.offerUnsafe(queue, { _tag: "Update", path }) return } } diff --git a/test-schemapart.mjs b/test-schemapart.mjs deleted file mode 100644 index 07757023de..0000000000 --- a/test-schemapart.mjs +++ /dev/null @@ -1,51 +0,0 @@ -import * as Check from "#dist/effect/schema/Check" -import * as Schema from "#dist/effect/schema/Schema" - -// Test SchemaPart examples -// Example 1: Basic SchemaPart Usage -const stringPart = Schema.String -const numberPart = Schema.Number -const bigintPart = Schema.BigInt - -// Example 2: Template Literal with Schema Parts -const userIdSchema = Schema.TemplateLiteral([ - "user-", - Schema.Number, // SchemaPart - "-", - Schema.String // SchemaPart -]) - -// Valid: "user-123-john" -const validUserId = Schema.decodeUnknownSync(userIdSchema)("user-123-john") -console.log(validUserId) // "user-123-john" - -// Example 3: Custom Schema Part with Constraints -const positiveNumberPart = Schema.Number.check(Check.positive()) -const nonEmptyStringPart = Schema.String.check(Check.nonEmpty()) - -// Use in template literal -const productCodeSchema = Schema.TemplateLiteral([ - "PRD-", - positiveNumberPart, - "-", - nonEmptyStringPart -]) - -// Valid: "PRD-123-widget" -const validProductCode = Schema.decodeUnknownSync(productCodeSchema)("PRD-123-widget") -console.log(validProductCode) // "PRD-123-widget" - -// Example 4: Type-Level Usage -function createVersionedTemplate(prefix, versionPart) { - return Schema.TemplateLiteral([prefix, versionPart]) -} - -// Usage with different schema parts -const versionWithNumber = createVersionedTemplate("v", Schema.Number) -const versionWithString = createVersionedTemplate("v", Schema.String) - -// Validate version patterns -const validVersion = Schema.decodeUnknownSync(versionWithNumber)("v123") -console.log(validVersion) // "v123" - -console.log("All SchemaPart examples compile successfully!")