~statianzo/janet-hashids

758171162613005845aedebcc4ccc5e1196fd0b4 — Jason Staten 4 years ago 827f9d1
refactor shuffle code
1 files changed, 18 insertions(+), 16 deletions(-)

M hashids.janet
M hashids.janet => hashids.janet +18 -16
@@ 12,25 12,27 @@

(def GUARD_DIV 12)

(defn- swap [arr i j]
  (def a (get arr j))
  (def b (get arr i))
  (put arr i a)
  (put arr j b)
)

(defn consistent-shuffle [alphabet salt]
  (if (= "" salt) alphabet
    (let [alph-bytes (apply array (string/bytes alphabet))
          salt-bytes (string/bytes salt)]
      (var p 0)

      (loop [i :down [(- (length alph-bytes) 1) 0]]
        (let [v (mod (- (length alph-bytes) i 1) (length salt-bytes))
              n (get salt-bytes v)]
          (set p (+ p n))
          (def j (mod (+ n v p) i))
          (def a (get alph-bytes j))
          (def b (get alph-bytes i))
          (put alph-bytes i a)
          (put alph-bytes j b)
          ))

      (apply string/from-bytes alph-bytes))))
      (let [alph-bytes (apply array (string/bytes alphabet))
            salt-bytes (string/bytes salt)
            max-index (- (length alph-bytes) 1)]
        (var p 0)

        (loop [i :down [max-index 0]]
          (let [v (mod (- max-index i) (length salt-bytes))
                n (get salt-bytes v)
                j (mod (+ n v (set p (+ p n))) i)]
            (swap alph-bytes i j)))

        (apply string/from-bytes alph-bytes))))


(defn encode [opts num]