Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Struct.ts

980 lines28.1 KB

1/**
2 * Works with plain TypeScript objects, also called structs.
3 *
4 * The runtime helpers in this module create new objects instead of mutating
5 * their inputs. They cover common object workflows such as reading properties,
6 * listing typed keys, picking or omitting fields, assigning and renaming keys,
7 * transforming values, deriving comparison helpers, and creating records from a
8 * list of keys. The module also includes type-level helpers for simplifying and
9 * merging object shapes.
10 *
11 * @since 2.0.0
12 */
13​
14import * as Combiner from "./Combiner.ts"
15import * as Equivalence from "./Equivalence.ts"
16import { dual } from "./Function.ts"
17import * as InternalRecord from "./internal/record.ts"
18import * as order from "./Order.ts"
19import * as Reducer from "./Reducer.ts"
20​
21/**
22 * Flattens intersection types into a single object type for readability.
23 *
24 * **When to use**
25 *
26 * Use when hovering over a type shows `A & B & C` instead of the merged shape.
27 *
28 * **Details**
29 *
30 * This helper is purely cosmetic at the type level and has no runtime effect.
31 * It preserves `readonly` modifiers; use {@link Mutable} to strip them.
32 *
33 * **Example** (Flattening an intersection)
34 *
35 * ```ts
36 * import type { Struct } from "effect"
37 *
38 * type Original = { a: string } & { b: number }
39 *
40 * // Without Simplify, the type displays as `{ a: string } & { b: number }`
41 * type Simplified = Struct.Simplify<Original>
42 * // { a: string; b: number }
43 * ```
44 *
45 * @see {@link Mutable} – also flattens but removes `readonly`
46 * @see {@link Assign} – merges two types with right-side precedence
47 * @category utility types
48 * @since 4.0.0
49 */
50export type Simplify<T> = { [K in keyof T]: T[K] } & {}
51​
52/**
53 * Removes `readonly` modifiers from all properties of an object type.
54 *
55 * **When to use**
56 *
57 * Use when you need a mutable version of a readonly interface.
58 *
59 * **Details**
60 *
61 * This helper is purely cosmetic at the type level and has no runtime effect.
62 * It also flattens intersections like {@link Simplify}.
63 *
64 * **Example** (Making a readonly type mutable)
65 *
66 * ```ts
67 * import type { Struct } from "effect"
68 *
69 * type ReadOnly = { readonly a: string; readonly b: number }
70 * type Writable = Struct.Mutable<ReadOnly>
71 * // { a: string; b: number }
72 * ```
73 *
74 * @see {@link Simplify} – flattens intersections without removing `readonly`
75 * @category utility types
76 * @since 4.0.0
77 */
78export type Mutable<T> = { -readonly [K in keyof T]: T[K] } & {}
79​
80/**
81 * Merges two object types with properties from `U` taking precedence over `T`
82 * on overlapping keys (like `Object.assign` at the type level).
83 *
84 * **When to use**
85 *
86 * Use when you need the type-level equivalent of `{ ...T, ...U }`.
87 *
88 * **Details**
89 *
90 * When no keys overlap, this returns a simple intersection for efficiency.
91 * When keys overlap, the type from `U` wins.
92 *
93 * **Example** (Merging two types with overlapping keys)
94 *
95 * ```ts
96 * import type { Struct } from "effect"
97 *
98 * type A = { a: string; b: number }
99 * type B = { b: boolean; c: string }
100 * type Merged = Struct.Assign<A, B>
101 * // { a: string; b: boolean; c: string }
102 * ```
103 *
104 * @see {@link assign} – the runtime equivalent
105 * @see {@link Simplify} – flatten the resulting intersection
106 * @category utility types
107 * @since 4.0.0
108 */
109export type Assign<T, U> = Simplify<keyof T & keyof U extends never ? T & U : Omit<T, keyof T & keyof U> & U>
110​
111/**
112 * Retrieves the value at `key` from a struct.
113 *
114 * **When to use**
115 *
116 * Use to extract a single property from a struct in a pipeline.
117 *
118 * **Details**
119 *
120 * The return type is narrowed to `S[K]`.
121 *
122 * **Example** (Extracting a property in a pipeline)
123 *
124 * ```ts
125 * import { pipe, Struct } from "effect"
126 *
127 * const name = pipe({ name: "Alice", age: 30 }, Struct.get("name"))
128 * console.log(name) // "Alice"
129 * ```
130 *
131 * @see {@link keys} – list all string keys of a struct
132 * @see {@link pick} – extract multiple properties into a new struct
133 * @category getters
134 * @since 2.0.0
135 */
136export const get: {
137 <S extends object, const K extends keyof S>(key: K): (self: S) => S[K]
138 <S extends object, const K extends keyof S>(self: S, key: K): S[K]
139} = dual(2, <S extends object, const K extends keyof S>(self: S, key: K): S[K] => self[key])
140​
141/**
142 * Returns the string keys of a struct as a properly typed `Array<keyof S & string>`.
143 *
144 * **When to use**
145 *
146 * Use when you want a typed replacement for `Object.keys` that narrows the result
147 * to the known string keys of the struct.
148 *
149 * **Gotchas**
150 *
151 * Symbol keys are excluded; only string keys are returned.
152 *
153 * **Example** (Reading typed keys)
154 *
155 * ```ts
156 * import { Struct } from "effect"
157 *
158 * const user = { name: "Alice", age: 30, [Symbol.for("id")]: 1 }
159 *
160 * const k: Array<"name" | "age"> = Struct.keys(user)
161 * console.log(k) // ["name", "age"]
162 * ```
163 *
164 * @see {@link get} – access a single key's value
165 * @see {@link pick} – select a subset of keys into a new struct
166 * @category Key utilities
167 * @since 3.6.0
168 */
169export const keys = <S extends object>(self: S): Array<(keyof S) & string> =>
170 Object.keys(self) as Array<(keyof S) & string>
171​
172/**
173 * Creates a new struct containing only the specified keys.
174 *
175 * **When to use**
176 *
177 * Use to narrow a struct down to a subset of its properties.
178 *
179 * **Gotchas**
180 *
181 * Keys not present in the struct are silently ignored.
182 *
183 * **Example** (Selecting specific properties)
184 *
185 * ```ts
186 * import { pipe, Struct } from "effect"
187 *
188 * const user = { name: "Alice", age: 30, admin: true }
189 * const nameAndAge = pipe(user, Struct.pick(["name", "age"]))
190 * console.log(nameAndAge) // { name: "Alice", age: 30 }
191 * ```
192 *
193 * @see {@link omit} – the inverse (exclude keys instead)
194 * @see {@link get} – extract a single value
195 * @category filtering
196 * @since 2.0.0
197 */
198export const pick: {
199 <S extends object, const Keys extends ReadonlyArray<keyof S>>(
200 keys: Keys
201 ): (self: S) => Simplify<Pick<S, Keys[number]>>
202 <S extends object, const Keys extends ReadonlyArray<keyof S>>(self: S, keys: Keys): Simplify<Pick<S, Keys[number]>>
203} = dual(
204 2,
205 <S extends object, const Keys extends ReadonlyArray<keyof S>>(self: S, keys: Keys) => {
206 return buildStruct(self, (k, v) => (keys.includes(k) ? [k, v] : undefined))
207 }
209​
210/**
211 * Creates a new struct with the specified keys removed.
212 *
213 * **When to use**
214 *
215 * Use to exclude sensitive or irrelevant fields from a struct.
216 *
217 * **Gotchas**
218 *
219 * Keys not present in the struct are silently ignored.
220 *
221 * **Example** (Removing a property)
222 *
223 * ```ts
224 * import { pipe, Struct } from "effect"
225 *
226 * const user = { name: "Alice", age: 30, password: "secret" }
227 * const safe = pipe(user, Struct.omit(["password"]))
228 * console.log(safe) // { name: "Alice", age: 30 }
229 * ```
230 *
231 * @see {@link pick} – the inverse (keep only specified keys)
232 * @category filtering
233 * @since 2.0.0
234 */
235export const omit: {
236 <S extends object, const Keys extends ReadonlyArray<keyof S>>(
237 keys: Keys
238 ): (self: S) => Simplify<Omit<S, Keys[number]>>
239 <S extends object, const Keys extends ReadonlyArray<keyof S>>(self: S, keys: Keys): Simplify<Omit<S, Keys[number]>>
240} = dual(
241 2,
242 <S extends object, Keys extends ReadonlyArray<keyof S>>(self: S, keys: Keys) => {
243 return buildStruct(self, (k, v) => (!keys.includes(k) ? [k, v] : undefined))
244 }
246​
247/**
248 * Merges two structs into a new struct. When both structs share a key, the
249 * value from `that` (the second struct) wins.
250 *
251 * **When to use**
252 *
253 * Use when you want `{ ...self, ...that }` with proper types.
254 *
255 * **Details**
256 *
257 * The result type is `Simplify<Assign<S, O>>`.
258 *
259 * **Example** (Merging structs with overlapping keys)
260 *
261 * ```ts
262 * import { pipe, Struct } from "effect"
263 *
264 * const defaults = { theme: "light", lang: "en" }
265 * const overrides = { theme: "dark", fontSize: 14 }
266 * const config = pipe(defaults, Struct.assign(overrides))
267 * console.log(config) // { theme: "dark", lang: "en", fontSize: 14 }
268 * ```
269 *
270 * @see {@link Assign} – the type-level equivalent
271 * @see {@link evolve} – transform individual values instead of replacing them
272 * @category combining
273 * @since 4.0.0
274 */
275export const assign: {
276 <O extends object>(that: O): <S extends object>(self: S) => Assign<S, O>
277 <O extends object, S extends object>(self: S, that: O): Assign<S, O>
278} = dual(
279 2,
280 <O extends object, S extends object>(self: S, that: O) => {
281 return { ...self, ...that }
282 }
284​
285type Evolver<S> = { readonly [K in keyof S]?: (a: S[K]) => unknown }
286​
287type Evolved<S, E> = Simplify<
288 { [K in keyof S]: K extends keyof E ? (E[K] extends (...a: any) => infer R ? R : S[K]) : S[K] }
290​
291/**
292 * Transforms values of a struct selectively using per-key functions. Keys
293 * without a corresponding function are copied unchanged.
294 *
295 * **When to use**
296 *
297 * Use when you want to update specific fields while keeping the rest intact.
298 *
299 * **Details**
300 *
301 * Each transform function receives the current value and returns the new value;
302 * the return type can differ from the input type.
303 *
304 * **Example** (Transforming selected values)
305 *
306 * ```ts
307 * import { pipe, Struct } from "effect"
308 *
309 * const result = pipe(
310 * { name: "alice", age: 30, active: true },
311 * Struct.evolve({
312 * name: (s) => s.toUpperCase(),
313 * age: (n) => n + 1
314 * })
315 * )
316 * console.log(result) // { name: "ALICE", age: 31, active: true }
317 * ```
318 *
319 * @see {@link evolveKeys} – transform keys instead of values
320 * @see {@link evolveEntries} – transform both keys and values
321 * @see {@link map} – apply the same transformation to all values
322 * @category transforming
323 * @since 2.0.0
324 */
325export const evolve: {
326 <S extends object, E extends Evolver<S>>(e: E): (self: S) => Evolved<S, E>
327 <S extends object, E extends Evolver<S>>(self: S, e: E): Evolved<S, E>
328} = dual(
329 2,
330 <S extends object, E extends Evolver<S>>(self: S, e: E): Evolved<S, E> => {
331 return buildStruct(self, (k, v) => [k, Object.hasOwn(e, k) ? (e as any)[k](v) : v])
332 }
334​
335type KeyEvolver<S> = { readonly [K in keyof S]?: (k: K) => PropertyKey }
336​
337type KeyEvolved<S, E> = Simplify<
338 { [K in keyof S as K extends keyof E ? (E[K] extends ((k: K) => infer R extends PropertyKey) ? R : K) : K]: S[K] }
340​
341/**
342 * Transforms keys of a struct selectively using per-key functions. Keys without
343 * a corresponding function are copied unchanged.
344 *
345 * **When to use**
346 *
347 * Use when you need computed key names, such as uppercasing or prefixing.
348 *
349 * **Details**
350 *
351 * Each transform function receives the key name and must return a new
352 * `PropertyKey`.
353 *
354 * **Example** (Renaming keys with functions)
355 *
356 * ```ts
357 * import { pipe, Struct } from "effect"
358 *
359 * const result = pipe(
360 * { name: "Alice", age: 30 },
361 * Struct.evolveKeys({
362 * name: (k) => k.toUpperCase()
363 * })
364 * )
365 * console.log(result) // { NAME: "Alice", age: 30 }
366 * ```
367 *
368 * @see {@link renameKeys} – rename keys with a static mapping
369 * @see {@link evolve} – transform values instead of keys
370 * @see {@link evolveEntries} – transform both keys and values
371 * @category Key utilities
372 * @since 4.0.0
373 */
374export const evolveKeys: {
375 <S extends object, E extends KeyEvolver<S>>(e: E): (self: S) => KeyEvolved<S, E>
376 <S extends object, E extends KeyEvolver<S>>(self: S, e: E): KeyEvolved<S, E>
377} = dual(
378 2,
379 <S extends object, E extends KeyEvolver<S>>(self: S, e: E): KeyEvolved<S, E> => {
380 return buildStruct(self, (k, v) => [Object.hasOwn(e, k) ? (e as any)[k](k) : k, v])
381 }
383​
384type EntryEvolver<S> = { readonly [K in keyof S]?: (k: K, v: S[K]) => [PropertyKey, unknown] }
385​
386type EntryEvolved<S, E> = {
387 [
388 K in keyof S as K extends keyof E ?
389 E[K] extends ((k: K, v: S[K]) => [infer NK extends PropertyKey, infer _V]) ? NK : K
390 : K
391 ]: K extends keyof E ? E[K] extends ((k: K, v: S[K]) => [infer _NK, infer V]) ? V
392 : S[K] :
393 S[K]
395​
396/**
397 * Transforms both keys and values of a struct selectively. Each per-key
398 * function receives `(key, value)` and must return a `[newKey, newValue]`
399 * tuple. Keys without a corresponding function are copied unchanged.
400 *
401 * **When to use**
402 *
403 * Use when you need to rename a key and change its value in one step.
404 *
405 * **Details**
406 *
407 * The return type is fully tracked at the type level.
408 *
409 * **Example** (Transforming keys and values together)
410 *
411 * ```ts
412 * import { pipe, Struct } from "effect"
413 *
414 * const result = pipe(
415 * { amount: 100, label: "total" },
416 * Struct.evolveEntries({
417 * amount: (k, v) => [`${k}Cents`, v * 100],
418 * label: (k, v) => [k, v.toUpperCase()]
419 * })
420 * )
421 * console.log(result) // { amountCents: 10000, label: "TOTAL" }
422 * ```
423 *
424 * @see {@link evolve} – transform values only
425 * @see {@link evolveKeys} – transform keys only
426 * @category transforming
427 * @since 4.0.0
428 */
429export const evolveEntries: {
430 <S extends object, E extends EntryEvolver<S>>(e: E): (self: S) => EntryEvolved<S, E>
431 <S extends object, E extends EntryEvolver<S>>(self: S, e: E): EntryEvolved<S, E>
432} = dual(
433 2,
434 <S extends object, E extends EntryEvolver<S>>(self: S, e: E): EntryEvolved<S, E> => {
435 return buildStruct(self, (k, v) => (Object.hasOwn(e, k) ? (e as any)[k](k, v) : [k, v]))
436 }
438​
439/**
440 * Renames keys in a struct using a static `{ oldKey: newKey }` mapping. Keys
441 * not mentioned in the mapping are copied unchanged.
442 *
443 * **When to use**
444 *
445 * Use when you need simple, declarative key renaming without custom logic.
446 *
447 * **Details**
448 *
449 * For computed key names, use {@link evolveKeys} instead.
450 *
451 * **Example** (Renaming keys)
452 *
453 * ```ts
454 * import { pipe, Struct } from "effect"
455 *
456 * const result = pipe(
457 * { firstName: "Alice", lastName: "Smith", age: 30 },
458 * Struct.renameKeys({ firstName: "first", lastName: "last" })
459 * )
460 * console.log(result) // { first: "Alice", last: "Smith", age: 30 }
461 * ```
462 *
463 * @see {@link evolveKeys} – rename keys using functions
464 * @see {@link evolveEntries} – rename keys and transform values
465 * @category Key utilities
466 * @since 4.0.0
467 */
468export const renameKeys: {
469 <S extends object, const M extends { readonly [K in keyof S]?: PropertyKey }>(
470 mapping: M
471 ): (self: S) => { [K in keyof S as K extends keyof M ? M[K] extends PropertyKey ? M[K] : K : K]: S[K] }
472 <S extends object, const M extends { readonly [K in keyof S]?: PropertyKey }>(
473 self: S,
474 mapping: M
475 ): { [K in keyof S as K extends keyof M ? M[K] extends PropertyKey ? M[K] : K : K]: S[K] }
476} = dual(2, <S extends object, const M extends { readonly [K in keyof S]?: PropertyKey }>(self: S, mapping: M) => {
477 return buildStruct(self, (k, v) => [Object.hasOwn(mapping, k) ? mapping[k]! : k, v])
478})
479​
480/**
481 * Creates an `Equivalence` for a struct by providing an `Equivalence` for each
482 * property. Two structs are equivalent when all their corresponding properties
483 * are equivalent.
484 *
485 * **When to use**
486 *
487 * Use when you need equality for a record-like object to be decided field by
488 * field, with a custom equality rule for each property.
489 *
490 * **Details**
491 *
492 * This is an alias of `Equivalence.Struct`. Each property's equivalence is
493 * checked independently; all must return `true` for the overall result to be
494 * `true`.
495 *
496 * **Example** (Comparing structs for equivalence)
497 *
498 * ```ts
499 * import { Equivalence, Struct } from "effect"
500 *
501 * const PersonEquivalence = Struct.makeEquivalence({
502 * name: Equivalence.strictEqual<string>(),
503 * age: Equivalence.strictEqual<number>()
504 * })
505 *
506 * console.log(PersonEquivalence({ name: "Alice", age: 30 }, { name: "Alice", age: 30 }))
507 * // true
508 * console.log(PersonEquivalence({ name: "Alice", age: 30 }, { name: "Bob", age: 30 }))
509 * // false
510 * ```
511 *
512 * @see {@link makeOrder} – create an `Order` for structs
513 * @category instances
514 * @since 4.0.0
515 */
516export const makeEquivalence = Equivalence.Struct
517​
518/**
519 * Creates an `Order` for a struct by providing an `Order` for each property.
520 * Properties are compared in the order they appear in the fields object; the
521 * first non-zero comparison determines the result.
522 *
523 * **When to use**
524 *
525 * Use when you need to sort record-like objects lexicographically by several
526 * fields, with each field using its own ordering rule.
527 *
528 * **Details**
529 *
530 * This is an alias of `Order.Struct`. The order of keys in the `fields` object
531 * determines comparison priority.
532 *
533 * **Example** (Ordering structs by name then age)
534 *
535 * ```ts
536 * import { Number, String, Struct } from "effect"
537 *
538 * const PersonOrder = Struct.makeOrder({
539 * name: String.Order,
540 * age: Number.Order
541 * })
542 *
543 * console.log(PersonOrder({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }))
544 * // -1 (Alice comes before Bob)
545 * ```
546 *
547 * @see {@link makeEquivalence} – create an `Equivalence` for structs
548 * @category ordering
549 * @since 4.0.0
550 */
551export const makeOrder = order.Struct
552​
553/**
554 * Interface for type-level functions used by {@link map}, {@link mapPick}, and
555 * {@link mapOmit}.
556 *
557 * **When to use**
558 *
559 * Use when defining a typed function for {@link map}, {@link mapPick}, or
560 * {@link mapOmit}.
561 *
562 * **Details**
563 *
564 * Extend this interface with concrete `~lambda.in` and `~lambda.out` types to
565 * describe how a function transforms values at the type level. At runtime,
566 * create lambda values with {@link lambda}.
567 *
568 * **Example** (Defining a lambda type)
569 *
570 * ```ts
571 * import type { Struct } from "effect"
572 *
573 * interface ToString extends Struct.Lambda {
574 * readonly "~lambda.out": string
575 * }
576 * ```
577 *
578 * @see {@link Apply} – apply a Lambda to a concrete type
579 * @see {@link lambda} – create a runtime lambda value
580 * @see {@link map} – use a lambda to transform all struct values
581 * @category Lambda
582 * @since 4.0.0
583 */
584export interface Lambda {
585 readonly "~lambda.in": unknown
586 readonly "~lambda.out": unknown
588​
589/**
590 * Applies a {@link Lambda} type-level function to a value type `V`, producing
591 * the output type.
592 *
593 * **When to use**
594 *
595 * Use when you need to compute what type a Lambda would produce for a
596 * given input.
597 *
598 * **Details**
599 *
600 * This works by intersecting the Lambda with `{ "~lambda.in": V }` and reading
601 * `"~lambda.out"`.
602 *
603 * **Example** (Computing the output type of a lambda)
604 *
605 * ```ts
606 * import type { Struct } from "effect"
607 *
608 * interface ToString extends Struct.Lambda {
609 * readonly "~lambda.out": string
610 * }
611 *
612 * // Result is `string`
613 * type Result = Struct.Apply<ToString, number>
614 * ```
615 *
616 * @see {@link Lambda} – the base interface
617 * @category Lambda
618 * @since 4.0.0
619 */
620export type Apply<L extends Lambda, V> = (L & { readonly "~lambda.in": V })["~lambda.out"]
621​
622/**
623 * Wraps a plain function as a {@link Lambda} value so it can be used with
624 * {@link map}, {@link mapPick}, and {@link mapOmit}.
625 *
626 * **When to use**
627 *
628 * Use to create a typed lambda for struct mapping APIs that need type-level
629 * input and output tracking.
630 *
631 * **Details**
632 *
633 * The type parameter `L` encodes both the input and output types at the type
634 * level, allowing the compiler to track how struct value types change. At
635 * runtime, the returned value is the same function; `lambda` only adjusts the
636 * type.
637 *
638 * **Example** (Wrapping values in arrays)
639 *
640 * ```ts
641 * import { pipe, Struct } from "effect"
642 *
643 * interface AsArray extends Struct.Lambda {
644 * <A>(self: A): Array<A>
645 * readonly "~lambda.out": Array<this["~lambda.in"]>
646 * }
647 *
648 * const asArray = Struct.lambda<AsArray>((a) => [a])
649 * const result = pipe({ x: 1, y: "hello" }, Struct.map(asArray))
650 * console.log(result) // { x: [1], y: ["hello"] }
651 * ```
652 *
653 * @see {@link Lambda} – the type-level interface
654 * @see {@link map} – apply a lambda to all struct values
655 * @category Lambda
656 * @since 4.0.0
657 */
658export const lambda = <L extends (a: any) => any>(
659 f: (a: Parameters<L>[0]) => ReturnType<L>
660): L => f as any
661​
662/**
663 * Applies a {@link Lambda} transformation to every value in a struct.
664 *
665 * **When to use**
666 *
667 * Use when you want to apply the same function to every value in a struct.
668 *
669 * **Details**
670 *
671 * The lambda must be created with {@link lambda} so the compiler can track the
672 * output types.
673 *
674 * **Example** (Wrapping every value in an array)
675 *
676 * ```ts
677 * import { pipe, Struct } from "effect"
678 *
679 * interface AsArray extends Struct.Lambda {
680 * <A>(self: A): Array<A>
681 * readonly "~lambda.out": Array<this["~lambda.in"]>
682 * }
683 *
684 * const asArray = Struct.lambda<AsArray>((a) => [a])
685 * const result = pipe({ width: 10, height: 20 }, Struct.map(asArray))
686 * console.log(result) // { width: [10], height: [20] }
687 * ```
688 *
689 * @see {@link mapPick} – apply a lambda only to selected keys
690 * @see {@link mapOmit} – apply a lambda to all keys except selected ones
691 * @see {@link evolve} – apply different functions to different keys
692 * @category mapping
693 * @since 4.0.0
694 */
695export const map: {
696 <L extends Lambda>(
697 lambda: L
698 ): <S extends object>(self: S) => { [K in keyof S]: Apply<L, S[K]> }
699 <S extends object, L extends Lambda>(
700 self: S,
701 lambda: L
702 ): { [K in keyof S]: Apply<L, S[K]> }
703} = dual(
704 2,
705 <S extends object, L extends Function>(self: S, lambda: L) => {
706 return buildStruct(self, (k, v) => [k, lambda(v)])
707 }
709​
710/**
711 * Applies a {@link Lambda} transformation only to the specified keys; all
712 * other keys are copied unchanged.
713 *
714 * **When to use**
715 *
716 * Use when you want to apply the same transformation to a subset of properties.
717 *
718 * **Example** (Wrapping only selected values in arrays)
719 *
720 * ```ts
721 * import { pipe, Struct } from "effect"
722 *
723 * interface AsArray extends Struct.Lambda {
724 * <A>(self: A): Array<A>
725 * readonly "~lambda.out": Array<this["~lambda.in"]>
726 * }
727 *
728 * const asArray = Struct.lambda<AsArray>((a) => [a])
729 * const result = pipe(
730 * { x: 1, y: 2, z: 3 },
731 * Struct.mapPick(["x", "z"], asArray)
732 * )
733 * console.log(result) // { x: [1], y: 2, z: [3] }
734 * ```
735 *
736 * @see {@link map} – apply a lambda to all keys
737 * @see {@link mapOmit} – apply a lambda to all keys except selected ones
738 * @category mapping
739 * @since 4.0.0
740 */
741export const mapPick: {
742 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Lambda>(
743 keys: Keys,
744 lambda: L
745 ): (
746 self: S
747 ) => { [K in keyof S]: K extends Keys[number] ? Apply<L, S[K]> : S[K] }
748 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Lambda>(
749 self: S,
750 keys: Keys,
751 lambda: L
752 ): { [K in keyof S]: K extends Keys[number] ? Apply<L, S[K]> : S[K] }
753} = dual(
754 3,
755 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Function>(
756 self: S,
757 keys: Keys,
758 lambda: L
759 ) => {
760 return buildStruct(self, (k, v) => [k, keys.includes(k) ? lambda(v) : v])
761 }
763​
764/**
765 * Applies a {@link Lambda} transformation to all keys except the specified
766 * ones; the excluded keys are copied unchanged.
767 *
768 * **When to use**
769 *
770 * Use when most keys should be transformed but a few should be preserved.
771 *
772 * **Example** (Wrapping all values except one in arrays)
773 *
774 * ```ts
775 * import { pipe, Struct } from "effect"
776 *
777 * interface AsArray extends Struct.Lambda {
778 * <A>(self: A): Array<A>
779 * readonly "~lambda.out": Array<this["~lambda.in"]>
780 * }
781 *
782 * const asArray = Struct.lambda<AsArray>((a) => [a])
783 * const result = pipe(
784 * { x: 1, y: 2, z: 3 },
785 * Struct.mapOmit(["y"], asArray)
786 * )
787 * console.log(result) // { x: [1], y: 2, z: [3] }
788 * ```
789 *
790 * @see {@link map} – apply a lambda to all keys
791 * @see {@link mapPick} – apply a lambda only to selected keys
792 * @category mapping
793 * @since 4.0.0
794 */
795export const mapOmit: {
796 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Lambda>(
797 keys: Keys,
798 lambda: L
799 ): (
800 self: S
801 ) => { [K in keyof S]: K extends Keys[number] ? S[K] : Apply<L, S[K]> }
802 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Lambda>(
803 self: S,
804 keys: Keys,
805 lambda: L
806 ): { [K in keyof S]: K extends Keys[number] ? S[K] : Apply<L, S[K]> }
807} = dual(
808 3,
809 <S extends object, const Keys extends ReadonlyArray<keyof S>, L extends Function>(
810 self: S,
811 keys: Keys,
812 lambda: L
813 ) => {
814 return buildStruct(self, (k, v) => [k, !keys.includes(k) ? lambda(v) : v])
815 }
817​
818/**
819 * Walk `source`; for each key decide what to emit via the small callback.
820 *
821 * The callback returns either
822 * • `undefined` → nothing is copied, or
823 * • `[newKey, newVal]`
824 *
825 * so every public API just supplies a different callback.
826 */
827function buildStruct<
828 S extends object,
829 f extends (k: keyof S, v: S[keyof S]) => [PropertyKey, unknown] | undefined
830>(
831 source: S,
832 f: f
833): any {
834 const out: Record<PropertyKey, unknown> = {}
835 for (const k of Reflect.ownKeys(source) as Array<keyof S>) {
836 if (!Object.prototype.propertyIsEnumerable.call(source, k)) continue
837 const res = f(k, source[k])
838 if (res) {
839 const [nk, nv] = res
840 InternalRecord.assignProperty(out, nk, nv)
841 }
842 }
843 return out
845​
846/**
847 * Creates a `Combiner` for a struct shape by providing a `Combiner` for each
848 * property. When two structs are combined, each property is merged using its
849 * corresponding combiner.
850 *
851 * **When to use**
852 *
853 * Use when you need to merge two same-shape records by combining each property
854 * independently, such as summing counters or concatenating strings.
855 *
856 * **Details**
857 *
858 * Pass `omitKeyWhen` to drop properties whose merged value matches a predicate,
859 * such as omitting zero counters.
860 *
861 * **Example** (Combining struct properties)
862 *
863 * ```ts
864 * import { Number, String, Struct } from "effect"
865 *
866 * const C = Struct.makeCombiner<{ readonly n: number; readonly s: string }>({
867 * n: Number.ReducerSum,
868 * s: String.ReducerConcat
869 * })
870 *
871 * const result = C.combine({ n: 1, s: "hello" }, { n: 2, s: " world" })
872 * console.log(result) // { n: 3, s: "hello world" }
873 * ```
874 *
875 * @see {@link makeReducer} – like `makeCombiner` but with an initial value
876 * @category combining
877 * @since 4.0.0
878 */
879export function makeCombiner<A>(
880 combiners: { readonly [K in keyof A]: Combiner.Combiner<A[K]> },
881 options?: {
882 readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
883 }
884): Combiner.Combiner<A> {
885 const omitKeyWhen = options?.omitKeyWhen ?? (() => false)
886 return Combiner.make((self, that) => {
887 const keys = Reflect.ownKeys(combiners) as Array<keyof A>
888 const out = {} as A
889 for (const key of keys) {
890 const merge = combiners[key].combine(self[key], that[key])
891 if (omitKeyWhen(merge)) continue
892 InternalRecord.assignProperty(out as object, key, merge)
893 }
894 return out
895 })
897​
898/**
899 * Creates a `Reducer` for a struct shape by providing a `Reducer` for each
900 * property. The initial value is derived from each property's
901 * `Reducer.initialValue`. When reducing a collection of structs, each property
902 * is combined independently.
903 *
904 * **When to use**
905 *
906 * Use when you need to fold same-shape records by accumulating each property
907 * independently into one summary record.
908 *
909 * **Details**
910 *
911 * Pass `omitKeyWhen` to drop properties whose reduced value matches a
912 * predicate.
913 *
914 * **Example** (Reducing a collection of structs)
915 *
916 * ```ts
917 * import { Number, String, Struct } from "effect"
918 *
919 * const R = Struct.makeReducer<{ readonly n: number; readonly s: string }>({
920 * n: Number.ReducerSum,
921 * s: String.ReducerConcat
922 * })
923 *
924 * const result = R.combineAll([
925 * { n: 1, s: "a" },
926 * { n: 2, s: "b" },
927 * { n: 3, s: "c" }
928 * ])
929 * console.log(result) // { n: 6, s: "abc" }
930 * ```
931 *
932 * @see {@link makeCombiner} – like `makeReducer` but without an initial value
933 * @category folding
934 * @since 4.0.0
935 */
936export function makeReducer<A>(
937 reducers: { readonly [K in keyof A]: Reducer.Reducer<A[K]> },
938 options?: {
939 readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
940 }
941): Reducer.Reducer<A> {
942 const combine = makeCombiner(reducers, options).combine
943 const initialValue = {} as A
944 for (const key of Reflect.ownKeys(reducers) as Array<keyof A>) {
945 const iv = reducers[key].initialValue
946 if (options?.omitKeyWhen?.(iv)) continue
947 InternalRecord.assignProperty(initialValue as object, key, iv)
948 }
949 return Reducer.make(combine, initialValue)
951​
952/**
953 * Creates a record with the given keys and value.
954 *
955 * **When to use**
956 *
957 * Use to build an object where each provided key receives the same value.
958 *
959 * **Example** (Creating a record)
960 *
961 * ```ts
962 * import { Struct } from "effect"
963 *
964 * const record = Struct.Record(["a", "b"], "value")
965 * console.log(record) // { a: "value", b: "value" }
966 * ```
967 *
968 * @category constructors
969 * @since 4.0.0
970 */
971export function Record<const Keys extends ReadonlyArray<string | symbol>, Value>(
972 keys: Keys,
973 value: Value
974): Record<Keys[number], Value> {
975 const out: any = {}
976 for (const key of keys) {
977 InternalRecord.assignProperty(out, key, value)
978 }
979 return out