Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/structs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ export function set<T>(Element?: Struct<T>): any {
schema: null,
*entries(value) {
if (Element && value instanceof Set) {
for (const v of value) {
for (const v of [...value]) {
yield [v as string, v, Element]
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ export function* run<T, S>(
yield [failure, undefined]
}

// `Set.add()` can only insert members, never replace one positionally, so a
// coerced element would accumulate alongside its original. Clear the set once
// on the first coerced write-back so only coerced members remain.
let clearedSet = false

for (let [k, v, s] of struct.entries(value, ctx)) {
const ts = run(v, s as Struct, {
path: k === undefined ? path : [...path, k],
Expand All @@ -174,6 +179,10 @@ export function* run<T, S>(
} else if (value instanceof Map) {
value.set(k, v)
} else if (value instanceof Set) {
if (!clearedSet) {
value.clear()
clearedSet = true
}
value.add(v)
} else if (isObject(value)) {
if (v !== undefined || k in value) value[k] = v
Expand Down
11 changes: 11 additions & 0 deletions test/validation/set/coerce-element.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { coerce, number, set, string } from '../../../src'

const toNumber = coerce(number(), string(), (v) => parseFloat(v))

export const Struct = set(toNumber)

export const data = new Set(['1', '2'])

export const output = new Set([1, 2])

export const create = true
Loading