From 4bcf345d7c757bb34ccd6c0cbdec9428f9d83985 Mon Sep 17 00:00:00 2001 From: Nikita Prokopov Date: Mon, 21 Oct 2024 14:31:59 +0200 Subject: [PATCH] Fixes read-handlers with multiple arities (closes #49) --- src/cognitect/transit.cljs | 32 +++++++++++++++++--------------- test/transit/test/core.cljs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/src/cognitect/transit.cljs b/src/cognitect/transit.cljs index 6ba787a..fb86ec2 100644 --- a/src/cognitect/transit.cljs +++ b/src/cognitect/transit.cljs @@ -115,21 +115,23 @@ (t/reader (name type) (opts-merge #js {:handlers - (clj->js - (merge - {"$" (fn [v] (symbol v)) - ":" (fn [v] (keyword v)) - "set" (fn [v] (into #{} v)) - "list" (fn [v] (into () (.reverse v))) - "cmap" (fn [v] - (loop [i 0 ret (transient {})] - (if (< i (alength v)) - (recur (+ i 2) - (assoc! ret (aget v i) (aget v (inc i)))) - (persistent! ret)))) - "with-meta" - (fn [v] (with-meta (aget v 0) (aget v 1)))} - (dissoc (:handlers opts) :default))) + (reduce-kv + (fn [m tag handler] + (gobj/set m (clj->js tag) #(handler %)) + m) + #js {"$" (fn [v] (symbol v)) + ":" (fn [v] (keyword v)) + "set" (fn [v] (into #{} v)) + "list" (fn [v] (into () (.reverse v))) + "cmap" (fn [v] + (loop [i 0 ret (transient {})] + (if (< i (alength v)) + (recur (+ i 2) + (assoc! ret (aget v i) (aget v (inc i)))) + (persistent! ret)))) + "with-meta" + (fn [v] (with-meta (aget v 0) (aget v 1)))} + (dissoc (:handlers opts) :default)) :defaultHandler (-> opts :handlers :default) :mapBuilder (MapBuilder.) :arrayBuilder (VectorBuilder.) diff --git a/test/transit/test/core.cljs b/test/transit/test/core.cljs index dc7ce5c..6cce15e 100644 --- a/test/transit/test/core.cljs +++ b/test/transit/test/core.cljs @@ -131,6 +131,36 @@ (is (= (t/read cr "[\"~:foo\", 1]") [:foo 1]))) +(deftest test-read-custom-arities + (is (= (t/read (t/reader :json + {:handlers + {"custom" (fn [x] + x)}}) + "[\"~#custom\",\"abc\"]") + "abc")) + (is (= (t/read (t/reader :json + {:handlers + {"custom" (fn + ([] nil) + ([x] x))}}) + "[\"~#custom\",\"abc\"]") + "abc")) + (is (= (t/read (t/reader :json + {:handlers + {"custom" (fn + ([x] x) + ([x y] [x y]))}}) + "[\"~#custom\",\"abc\"]") + "abc")) + (is (= (t/read (t/reader :json + {:handlers + {"custom" (fn + ([] nil) + ([x] x) + ([x y] [x y]))}}) + "[\"~#custom\",\"abc\"]") + "abc"))) + (def cw (t/writer :json {:handlers