Skip to content

Commit c0ba834

Browse files
titouancreachgcanti
authored andcommitted
add Schema.headNonEmpty on Schema.NonEmptyArray (#3983)
Co-authored-by: Giulio Canti <giulio.canti@gmail.com>
1 parent 642376c commit c0ba834

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": minor
3+
---
4+
5+
Add Schema.headNonEmpty for Schema.NonEmptyArray

packages/effect/src/Schema.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6117,6 +6117,19 @@ export const head = <A, I, R>(self: Schema<ReadonlyArray<A>, I, R>): SchemaClass
61176117
{ strict: true, decode: array_.head, encode: option_.match({ onNone: () => [], onSome: array_.of }) }
61186118
)
61196119

6120+
/**
6121+
* Get the first element of a `NonEmptyReadonlyArray`.
6122+
*
6123+
* @category NonEmptyReadonlyArray transformations
6124+
* @since 3.12.0
6125+
*/
6126+
export const headNonEmpty = <A, I, R>(self: Schema<array_.NonEmptyReadonlyArray<A>, I, R>): SchemaClass<A, I, R> =>
6127+
transform(
6128+
self,
6129+
getNumberIndexedAccess(typeSchema(self)),
6130+
{ strict: true, decode: array_.headNonEmpty, encode: array_.of }
6131+
)
6132+
61206133
/**
61216134
* Retrieves the first element of a `ReadonlyArray`.
61226135
*
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import * as S from "effect/Schema"
2+
import * as Util from "effect/test/Schema/TestUtils"
3+
import { describe, it } from "vitest"
4+
5+
describe("headNonEmpty", () => {
6+
it("decoding", async () => {
7+
const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))
8+
await Util.expectDecodeUnknownSuccess(schema, ["1"], 1)
9+
await Util.expectDecodeUnknownFailure(
10+
schema,
11+
["a"],
12+
`(readonly [NumberFromString, ...NumberFromString[]] <-> number | number)
13+
└─ Encoded side transformation failure
14+
└─ readonly [NumberFromString, ...NumberFromString[]]
15+
└─ [0]
16+
└─ NumberFromString
17+
└─ Transformation process failure
18+
└─ Expected NumberFromString, actual "a"`
19+
)
20+
})
21+
22+
it("encoding", async () => {
23+
const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))
24+
await Util.expectEncodeSuccess(schema, 1, ["1"])
25+
})
26+
})

0 commit comments

Comments
 (0)