Skip to content

Commit

Permalink
add Set::to_json
Browse files Browse the repository at this point in the history
  • Loading branch information
bobzhang committed Oct 12, 2024
1 parent 7d69952 commit 723b078
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ impl Set {
size[K](Self[K]) -> Int
symmetric_difference[K : Hash + Eq](Self[K], Self[K]) -> Self[K]
to_array[K](Self[K]) -> Array[K]
to_json[X : ToJson](Self[X]) -> Json
to_string[K : Show](Self[K]) -> String
union[K : Hash + Eq](Self[K], Self[K]) -> Self[K]
}
Expand Down
8 changes: 8 additions & 0 deletions builtin/json.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ pub fn Map::to_json[K : Show, V : ToJson](self : Map[K, V]) -> Json {
Object(object)
}

pub fn Set::to_json[X : ToJson](self : Set[X]) -> Json {
let array = []
for v in self {
array.push(v.to_json())
}
Array(array)
}

pub fn Option::to_json[T : ToJson](self : T?) -> Json {
match self {
None => Null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ test "insert_and_grow" {
}
assert_eq!(m.size(), 10)
assert_eq!(m.capacity(), 16)
@json.inspect!(m, content=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
}

test "array unique via Set" {
let v = [1, 2, 3, 4, 5, 3, 2, 4, 5]
let h = Set::from_iter(v.iter())
let v = [..h]
// @json.inspect!([..h])
@json.inspect!(v, content=[1, 2, 3, 4, 5])
}

test "remove_and_shift_back" {
Expand Down

0 comments on commit 723b078

Please sign in to comment.