diff options
author | sobolevn <mail@sobolevn.me> | 2024-08-19 23:49:53 +0300 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-08-24 13:07:53 +0100 |
commit | 55144a098040bf43871df4cf7b217e47f697c12b (patch) | |
tree | 466feffa9517b94474132c63ae28d0beded1b474 /src | |
parent | 8f9d8b1969270d0786cd4eeb369ed3d42a62e541 (diff) | |
download | gleam_stdlib-55144a098040bf43871df4cf7b217e47f697c12b.tar.gz gleam_stdlib-55144a098040bf43871df4cf7b217e47f697c12b.zip |
Fix js
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/bit_array.gleam | 13 | ||||
-rw-r--r-- | src/gleam_stdlib.mjs | 23 |
2 files changed, 35 insertions, 1 deletions
diff --git a/src/gleam/bit_array.gleam b/src/gleam/bit_array.gleam index 909d9f1..8c3ce48 100644 --- a/src/gleam/bit_array.gleam +++ b/src/gleam/bit_array.gleam @@ -204,7 +204,18 @@ fn do_inspect(input: BitArray, accumulator: String) -> String { /// // -> Eq /// ``` /// +/// Only supported on Erlang target for now. +/// pub fn compare(first: BitArray, second: BitArray) -> order.Order { + do_compare(first, second) +} + +@target(javascript) +@external(javascript, "../gleam_stdlib.mjs", "bit_array_compare") +fn do_compare(first: BitArray, second: BitArray) -> order.Order + +@target(erlang) +fn do_compare(first: BitArray, second: BitArray) -> order.Order { case first, second { <<first_byte, first_rest:bits>>, <<second_byte, second_rest:bits>> -> int.compare(first_byte, second_byte) @@ -217,11 +228,11 @@ pub fn compare(first: BitArray, second: BitArray) -> order.Order { <<>>, _ -> order.Lt // This happens when there's unusually sized elements. // Handle these special cases via custom erlang function. - // This cannot be reached in JS right now. first, second -> int.compare(bit_array_to_int(first), bit_array_to_int(second)) } } +@target(erlang) @external(erlang, "gleam_stdlib", "bit_array_to_int") fn bit_array_to_int(first: BitArray) -> Int diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index a89c829..9fe6caa 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -16,6 +16,7 @@ import { } from "./gleam/regex.mjs"; import { DecodeError } from "./gleam/dynamic.mjs"; import { Some, None } from "./gleam/option.mjs"; +import { Eq, Gt, Lt } from "./gleam/order.mjs"; import Dict from "./dict.mjs"; const Nil = undefined; @@ -916,3 +917,25 @@ export function base16_decode(string) { export function bit_array_inspect(bits, acc) { return `${acc}${[...bits.buffer].join(", ")}`; } + +export function bit_array_compare(first, second) { + for (let i = 0; i < first.length; i++) { + if (i >= second.length) { + return new Gt(); // first has more items + } + const f = first.buffer[i]; + const s = second.buffer[i]; + if (f > s) { + return new Gt(); + } + if (f < s) { + return new Lt() + } + } + // This means that either first did not have any items + // or all items in first were equal to second. + if (first.length === second.length) { + return new Eq(); + } + return new Lt(); // second has more items +} |