diff options
author | rubytree <rt@rubytree.me> | 2023-05-09 22:58:39 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-05-13 16:32:38 +0100 |
commit | 4fea7c8617aae705a30592c7661fca65f377979e (patch) | |
tree | d7eb992301688c376b59cc0deea125223a6e3ae8 /src/gleam_stdlib.mjs | |
parent | 037e2c575c367666a952f99ea4d9cc42268cedec (diff) | |
download | gleam_stdlib-4fea7c8617aae705a30592c7661fca65f377979e.tar.gz gleam_stdlib-4fea7c8617aae705a30592c7661fca65f377979e.zip |
Fix coerce errors messages, js tuple from list fixes
Diffstat (limited to 'src/gleam_stdlib.mjs')
-rw-r--r-- | src/gleam_stdlib.mjs | 33 |
1 files changed, 18 insertions, 15 deletions
diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index d9825e7..7c41cdd 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -637,26 +637,29 @@ export function decode_tuple6(data) { } function decode_tupleN(data, n) { - let error_message = `Tuple or List of ${n} elements`; - - if (!(List.isList(data) || Array.isArray(data))) { - return decoder_error(error_message, data); + if (Array.isArray(data) && data.length == n) { + return new Ok(data) } - let array = List.isList(data) ? [...data] : data; + let list = decode_exact_length_list(data, n) + if (list) return new Ok(list) - let i = 0; - for (; i < n; i++) { - if (array[i] === undefined) { - return decoder_error(error_message, data); - } - } + return decoder_error(`Tuple of ${n} elements`, data); +} - if (array[i] === undefined) { - return new Ok(array); - } else { - return decoder_error(error_message, data); +function decode_exact_length_list(data, n) { + if (!List.isList(data)) return; + + let elements = [] + let current = data + + for (let i = 0; i < n; i++) { + if (current.isEmpty()) break; + elements.push(current.head) + current = current.tail } + + if (elements.length === n && current.isEmpty()) return elements } export function tuple_get(data, index) { |