Skip to content

Commit

Permalink
add Schema.headNonEmpty on Schema.NonEmptyArray (#3983)
Browse files Browse the repository at this point in the history
Co-authored-by: Giulio Canti <[email protected]>
  • Loading branch information
titouancreach and gcanti committed Dec 10, 2024
1 parent 660d00d commit 20f55ec
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/violet-spoons-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Add Schema.headNonEmpty for Schema.NonEmptyArray
13 changes: 13 additions & 0 deletions packages/effect/src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6014,6 +6014,19 @@ export const head = <A, I, R>(self: Schema<ReadonlyArray<A>, I, R>): SchemaClass
{ strict: true, decode: array_.head, encode: option_.match({ onNone: () => [], onSome: array_.of }) }
)

/**
* Get the first element of a `NonEmptyReadonlyArray`.
*
* @category NonEmptyReadonlyArray transformations
* @since 3.12.0
*/
export const headNonEmpty = <A, I, R>(self: Schema<array_.NonEmptyReadonlyArray<A>, I, R>): SchemaClass<A, I, R> =>
transform(
self,
getNumberIndexedAccess(typeSchema(self)),
{ strict: true, decode: array_.headNonEmpty, encode: array_.of }
)

/**
* Retrieves the first element of a `ReadonlyArray`.
*
Expand Down
26 changes: 26 additions & 0 deletions packages/effect/test/Schema/Schema/Array/headNonEmpty.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as S from "effect/Schema"
import * as Util from "effect/test/Schema/TestUtils"
import { describe, it } from "vitest"

describe("headNonEmpty", () => {
it("decoding", async () => {
const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))
await Util.expectDecodeUnknownSuccess(schema, ["1"], 1)
await Util.expectDecodeUnknownFailure(
schema,
["a"],
`(readonly [NumberFromString, ...NumberFromString[]] <-> number | number)
└─ Encoded side transformation failure
└─ readonly [NumberFromString, ...NumberFromString[]]
└─ [0]
└─ NumberFromString
└─ Transformation process failure
└─ Expected NumberFromString, actual "a"`
)
})

it("encoding", async () => {
const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))
await Util.expectEncodeSuccess(schema, 1, ["1"])
})
})

0 comments on commit 20f55ec

Please sign in to comment.