From bb88a32d105da31e5cdd2ad713016c88b96ac0ce Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Thu, 9 Sep 2021 21:25:11 +0100 Subject: JS dynamic element --- src/gleam_stdlib.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/gleam_stdlib.js') diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js index 0982f62..9a80a6d 100644 --- a/src/gleam_stdlib.js +++ b/src/gleam_stdlib.js @@ -476,8 +476,12 @@ function classify_dynamic(data) { return "List"; } else if (Number.isInteger(data)) { return "Int"; + } else if (Array.isArray(data)) { + return `Tuple of ${data.length} elements`; } else if (BitString.isBitString(data)) { return "BitString"; + } else if (data instanceof Map) { + return "Map"; } else if (typeof data === "number") { return "Float"; } else { @@ -513,3 +517,25 @@ export function decode_bit_string(data) { ? new Ok(data) : decoder_error("BitString", data); } + +export function decode_element(data, index) { + let error = (size) => + decoder_error( + `Tuple of at least ${size} element${size > 1 ? "s" : ""}`, + data + ); + if (!Array.isArray(data)) return error(index < 0 ? 1 : index + 1); + if (index >= 0) { + if (index < data.length) { + return new Ok(data[index]); + } else { + return error(index + 1); + } + } else { + if (Math.abs(index) <= data.length) { + return new Ok(data[data.length + index]); + } else { + return error(Math.abs(index)); + } + } +} -- cgit v1.2.3