Skip to content

Commit 1be6de8

Browse files
CrowdHailerlpil
authored andcommitted
add decode1 function
1 parent a7fccb8 commit 1be6de8

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/gleam/dynamic.gleam

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -987,6 +987,33 @@ pub fn any(of decoders: List(Decoder(t))) -> Decoder(t) {
987987
}
988988
}
989989

990+
/// Decode 1 values from a `Dynamic` value.
991+
///
992+
/// ## Examples
993+
///
994+
/// ```gleam
995+
/// > from(#(1, 2.0, "3"))
996+
/// > |> decode1(MyRecord, element(0, int))
997+
/// Ok(MyRecord(1))
998+
/// ```
999+
///
1000+
/// ```gleam
1001+
/// > from(#("", "", ""))
1002+
/// > |> decode1(MyRecord, element(0, int))
1003+
/// Error([
1004+
/// DecodeError(expected: "Int", found: "String", path: ["0"]),
1005+
/// ])
1006+
/// ```
1007+
///
1008+
pub fn decode1(constructor: fn(t1) -> t, t1: Decoder(t1)) -> Decoder(t) {
1009+
fn(value) {
1010+
case t1(value) {
1011+
Ok(a) -> Ok(constructor(a))
1012+
a -> Error(all_errors(a))
1013+
}
1014+
}
1015+
}
1016+
9901017
/// Decode 2 values from a `Dynamic` value.
9911018
///
9921019
/// ## Examples

test/gleam/dynamic_test.gleam

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,26 @@ pub fn any_test() {
838838
|> should.equal(Error([DecodeError("another type", "String", path: [])]))
839839
}
840840

841+
type One(a) {
842+
One(a)
843+
}
844+
845+
pub fn decode1_test() {
846+
let decoder = dynamic.decode1(One, dynamic.element(0, dynamic.int))
847+
848+
#(1)
849+
|> dynamic.from
850+
|> decoder
851+
|> should.equal(Ok(One(1)))
852+
853+
#(1.3)
854+
|> dynamic.from
855+
|> decoder
856+
|> should.equal(Error([
857+
DecodeError(expected: "Int", found: "Float", path: ["0"]),
858+
]))
859+
}
860+
841861
type Two(a, b) {
842862
Two(a, b)
843863
}

0 commit comments

Comments
 (0)