From 749ac8290d1e3d09e2287056f618d6df91f4e01b Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Thu, 9 Sep 2021 20:01:04 +0100 Subject: JS dynamic bool --- src/gleam/dynamic.gleam | 35 +++++++++++++++++++++++------------ src/gleam_stdlib.js | 8 +++++++- 2 files changed, 30 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/gleam/dynamic.gleam b/src/gleam/dynamic.gleam index d4afca0..86d1b6e 100644 --- a/src/gleam/dynamic.gleam +++ b/src/gleam/dynamic.gleam @@ -159,21 +159,32 @@ if javascript { "../gleam_stdlib.js" "decode_float" } +/// Checks to see whether a Dynamic value is an bool, and return the bool if +/// it is. +/// +/// ## Examples +/// +/// > bool(from(True)) +/// Ok(True) +/// +/// > bool(from(123)) +/// Error(DecodeError(expected: "bool", found: "Int")) +/// +pub fn bool(from data: Dynamic) -> Result(Bool, DecodeError) { + decode_bool(data) +} + if erlang { - /// Checks to see whether a Dynamic value is an bool, and return the bool if - /// it is. - /// - /// ## Examples - /// - /// > bool(from(True)) - /// Ok(True) - /// - /// > bool(from(123)) - /// Error(DecodeError(expected: "bool", found: "Int")) - /// - pub external fn bool(from: Dynamic) -> Result(Bool, DecodeError) = + external fn decode_bool(Dynamic) -> Result(Bool, DecodeError) = "gleam_stdlib" "decode_bool" +} +if javascript { + external fn decode_bool(Dynamic) -> Result(Bool, DecodeError) = + "../gleam_stdlib.js" "decode_bool" +} + +if erlang { /// Checks to see whether a Dynamic value is a list, and return the list if it /// is. /// diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js index cfe26a2..b8feecf 100644 --- a/src/gleam_stdlib.js +++ b/src/gleam_stdlib.js @@ -476,8 +476,11 @@ function classify_dynamic(data) { return "List"; } else if (Number.isInteger(data)) { return "Int"; + } else if (typeof data === "number") { + return "Float"; } else { - return typeof data; + let type = typeof data; + return type.charAt(0).toUpperCase() + type.slice(1); } } @@ -498,3 +501,6 @@ export function decode_int(data) { export function decode_float(data) { return typeof data === "number" ? new Ok(data) : decoder_error("Float", data); } +export function decode_bool(data) { + return typeof data === "boolean" ? new Ok(data) : decoder_error("Bool", data); +} -- cgit v1.2.3