M hashids.janet => hashids.janet +47 -2
@@ 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")
M test/encode.janet => test/encode.janet +1 -1
@@ 1,7 1,7 @@
(import ../hashids :as h)
(assert
- (= "j0gW" (h/encode {} 12345)))
+ (= "j0gW" (h/encode 12345 :salt "nobody")))
#(assert
#(= "jR" (h/encode {} 1)))
A test/setup.janet => test/setup.janet +13 -0
@@ 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