Skip to content

Commit

Permalink
struct: evolve to skip unspecified transformations
Browse files Browse the repository at this point in the history
  • Loading branch information
imcotton committed Jun 12, 2022
1 parent 34b28fa commit 8c41dca
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,14 @@ export const getAssignSemigroup = <A extends object = never>(): Semigroup<A> =>
*
* @since 2.11.0
*/
export const evolve = <A, F extends { [K in keyof A]: (a: A[K]) => unknown }>(transformations: F) => (
export const evolve = <A, F extends { [K in keyof A]?: (a: A[K]) => unknown }>(transformations: F) => (
a: A
): { [K in keyof F]: ReturnType<F[K]> } => {
): { [K in keyof A]: F[K] extends (a: A[K]) => unknown ? ReturnType<F[K]> : A[K] } => {
const out: Record<string, unknown> = {}
for (const k in a) {
if (_.has.call(a, k)) {
out[k] = transformations[k](a[k])
const fn = transformations[k]
out[k] = typeof fn === 'function' ? fn(a[k]) : a[k]
}
}
return out as any
Expand Down
4 changes: 3 additions & 1 deletion test/struct.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pipe } from '../src/function'
import { pipe, increment } from '../src/function'
import * as _ from '../src/struct'
import * as U from './util'

Expand Down Expand Up @@ -35,5 +35,7 @@ describe('struct', () => {
const x: Record<'b', number> = Object.create({ a: 1 })
x.b = 1
U.deepStrictEqual(pipe(x, _.evolve({ b: (b) => b > 0 })), { b: true })
// does not invoke absent transformations
U.deepStrictEqual(pipe({ a: 1, b: 's' }, _.evolve({ a: increment })), { a: 2, b: 's' })
})
})

0 comments on commit 8c41dca

Please sign in to comment.