Skip to content

Commit fe9aa89

Browse files
committed
JS decode field for maps
1 parent ff8be8c commit fe9aa89

File tree

2 files changed

+34
-29
lines changed

2 files changed

+34
-29
lines changed

src/gleam_stdlib.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,14 @@ export function decode_option(data, decoder) {
556556
}
557557

558558
export function decode_field(value, name) {
559-
return name in value
560-
? new Ok(value[name])
561-
: decoder_error(`Value with field ${inspect(name)}`, value);
559+
let error = () => decoder_error(`Value with field ${inspect(name)}`, value);
560+
if (value instanceof Map) {
561+
let entry = value.get(name);
562+
return entry.isOk() ? entry : error();
563+
}
564+
try {
565+
return name in value ? new Ok(value[name]) : error();
566+
} catch {
567+
return error();
568+
}
562569
}

test/gleam/dynamic_test.gleam

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -246,36 +246,34 @@ if javascript {
246246
}
247247
}
248248

249-
if erlang {
250-
pub fn field_test() {
251-
map.new()
252-
|> map.insert("ok", 1)
253-
|> dynamic.from
254-
|> dynamic.field("ok")
255-
|> should.equal(Ok(dynamic.from(1)))
249+
pub fn field_test() {
250+
map.new()
251+
|> map.insert("ok", 1)
252+
|> dynamic.from
253+
|> dynamic.field("ok")
254+
|> should.equal(Ok(dynamic.from(1)))
256255

257-
map.new()
258-
|> map.insert("ok", 3)
259-
|> map.insert("error", 1)
260-
|> dynamic.from
261-
|> dynamic.field("ok")
262-
|> should.equal(Ok(dynamic.from(3)))
256+
map.new()
257+
|> map.insert("ok", 3)
258+
|> map.insert("error", 1)
259+
|> dynamic.from
260+
|> dynamic.field("ok")
261+
|> should.equal(Ok(dynamic.from(3)))
263262

264-
map.new()
265-
|> dynamic.from
266-
|> dynamic.field("ok")
267-
|> should.be_error
263+
map.new()
264+
|> dynamic.from
265+
|> dynamic.field("ok")
266+
|> should.be_error
268267

269-
1
270-
|> dynamic.from
271-
|> dynamic.field("ok")
272-
|> should.be_error
268+
1
269+
|> dynamic.from
270+
|> dynamic.field("ok")
271+
|> should.be_error
273272

274-
[]
275-
|> dynamic.from
276-
|> dynamic.field([])
277-
|> should.be_error
278-
}
273+
[]
274+
|> dynamic.from
275+
|> dynamic.field([])
276+
|> should.be_error
279277
}
280278

281279
pub fn element_test() {

0 commit comments

Comments
 (0)