Skip to content

Commit

Permalink
add ffi bindings for maps (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
CrowdHailer authored Aug 12, 2023
1 parent 6cbbfcb commit d5ba780
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Changelog

- Add `map` module native JavaScript maps.
- `promise.new` is added to enable creating promises with a delayed resolve.

## v0.5.0 - 2023-01-19
Expand Down
19 changes: 19 additions & 0 deletions src/ffi.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,22 @@ export function all_promises(...promises) {
return Promise.all(promises);
}
}

export function map_new() {
return new Map();
}

export function map_set(map, key, value) {
return map.set(key, value);
}

export function map_get(map, key) {
if (map.has(key)) {
return new Ok(map.get(key));
}
return new Error(undefined);
}

export function map_size(map) {
return map.size;
}
13 changes: 13 additions & 0 deletions src/gleam/javascript/map.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
pub type Map(key, value)

@external(javascript, "../../ffi.mjs", "map_new")
pub fn new() -> Map(key, value)

@external(javascript, "../../ffi.mjs", "map_set")
pub fn set(a: Map(key, value), b: key, c: value) -> Map(key, value)

@external(javascript, "../../ffi.mjs", "map_get")
pub fn get(a: Map(key, value), b: key) -> Result(value, Nil)

@external(javascript, "../../ffi.mjs", "map_size")
pub fn size(a: Map(key, value)) -> Int
27 changes: 27 additions & 0 deletions test/gleam/javascript/map_test.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import gleam/javascript/map
import gleeunit/should

pub fn map_size_test() {
let m = map.new()
should.equal(map.size(m), 0)

map.set(m, "a", 1)
should.equal(map.size(m), 1)

map.set(m, "b", 1)
should.equal(map.size(m), 2)

map.set(m, "b", 10)
should.equal(map.size(m), 2)
}

pub fn map_retrieve_test() {
let m = map.new()
should.equal(map.get(m, "a"), Error(Nil))

map.set(m, "a", 1)
should.equal(map.get(m, "a"), Ok(1))

map.set(m, "a", 2)
should.equal(map.get(m, "a"), Ok(2))
}

0 comments on commit d5ba780

Please sign in to comment.