From b14746dfbd67965772ca21405758f671b926a71c Mon Sep 17 00:00:00 2001 From: Hongbo Zhang Date: Sat, 12 Oct 2024 14:54:41 +0800 Subject: [PATCH] add Set::to_json --- builtin/builtin.mbti | 1 + builtin/json.mbt | 8 ++++++++ ...nked_hash_set_wbtest.mbt => linked_hash_set_test.mbt} | 9 +++++++++ 3 files changed, 18 insertions(+) rename builtin/{linked_hash_set_wbtest.mbt => linked_hash_set_test.mbt} (95%) diff --git a/builtin/builtin.mbti b/builtin/builtin.mbti index 8e67892b5..0de1f39f0 100644 --- a/builtin/builtin.mbti +++ b/builtin/builtin.mbti @@ -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] } diff --git a/builtin/json.mbt b/builtin/json.mbt index bd240c76c..f836b834c 100644 --- a/builtin/json.mbt +++ b/builtin/json.mbt @@ -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 diff --git a/builtin/linked_hash_set_wbtest.mbt b/builtin/linked_hash_set_test.mbt similarity index 95% rename from builtin/linked_hash_set_wbtest.mbt rename to builtin/linked_hash_set_test.mbt index 5648d18fc..04004ab64 100644 --- a/builtin/linked_hash_set_wbtest.mbt +++ b/builtin/linked_hash_set_test.mbt @@ -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" {