From 66c6d2bebd24d1236918c0a1d6c57b83fd372904 Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Fri, 22 May 2020 15:02:01 -0600 Subject: [PATCH] setup work --- hashids.janet | 49 +++++++++++++++++++++++++++++++++++++++++++++-- test/encode.janet | 2 +- test/setup.janet | 13 +++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 test/setup.janet diff --git a/hashids.janet b/hashids.janet index a5233f9..6d4b0a8 100644 --- a/hashids.janet +++ b/hashids.janet @@ -12,6 +12,20 @@ (def GUARD_DIV 12) +(def DEFAULTS {:salt DEFAULT_SALT + :min-length DEFAULT_MIN_LENGTH + :alphabet DEFAULT_ALPHABET + :seps DEFAULT_SEPS}) + +(defn- map-indexed [f xs] + (map f xs (range 0 (length xs)))) + +(defn- int-hash [num i] + (mod num (+ 100 i))) + +(defn- as-indexed [x] + (if (indexed? x) x [x])) + (defn- swap [arr i j] (def a (in arr j)) (def b (in arr i)) @@ -19,6 +33,12 @@ (put arr j b) ) +(defn- difference [s1 s2] + (seq [x :in s1 :when (not (find |(= x $) s2))] x)) + +(defn- intersection [s1 s2] + (seq [x :in s1 y :in s2 :when (= x y)] x)) + (defn consistent-shuffle [alphabet salt] (if (= "" salt) alphabet (let [alph-bytes (apply array (string/bytes alphabet)) @@ -34,6 +54,31 @@ (apply string/from-bytes alph-bytes)))) +(defn setup [opts] +(let [{:salt salt + :alphabet alphabet + :seps seps + :min-length min-length} (merge DEFAULTS opts) + alph-bytes (string/bytes alphabet) + salt-bytes (string/bytes salt) + seps-bytes (string/bytes seps) + unbalanced-alph (difference alph-bytes seps-bytes) + unbalanced-seps (intersection alph-bytes seps-bytes) + ] +(pp unbalanced-seps) +{ +:seps (apply string/from-bytes unbalanced-seps) +:alph (apply string/from-bytes unbalanced-alph) + :salt salt + :min-length min-length +})) + +(defn encode + "Convert nums to hashids encoded form" + [source & opts] + (let [config (setup (table ;opts)) + nums (as-indexed source) + hash-int (reduce + 0 (map-indexed int-hash nums))] + (pp config) + "j0gW")) -(defn encode [opts num] - "j0gW") diff --git a/test/encode.janet b/test/encode.janet index 0798cac..af8e799 100644 --- a/test/encode.janet +++ b/test/encode.janet @@ -1,7 +1,7 @@ (import ../hashids :as h) (assert - (= "j0gW" (h/encode {} 12345))) + (= "j0gW" (h/encode 12345 :salt "nobody"))) #(assert #(= "jR" (h/encode {} 1))) diff --git a/test/setup.janet b/test/setup.janet new file mode 100644 index 0000000..7a5eb74 --- /dev/null +++ b/test/setup.janet @@ -0,0 +1,13 @@ +(import ../hashids :as h) + +(let + [{:salt salt + :alphabet alphabet + :seps seps + :min-length min-length} (h/setup {})] + (assert (= h/DEFAULT_SALT salt)) + (assert (= h/DEFAULT_ALPHABET alphabet)) + + (assert (= h/DEFAULT_SEPS seps)) + (assert (= h/DEFAULT_MIN_LENGTH min-length)) +) \ No newline at end of file