Skip to content

Instantly share code, notes, and snippets.

@cloojure
Created July 31, 2019 16:42
Show Gist options
  • Save cloojure/8237f54ef8be604f5ce151feee336a16 to your computer and use it in GitHub Desktop.
Save cloojure/8237f54ef8be604f5ce151feee336a16 to your computer and use it in GitHub Desktop.
Replicating Java's String.hashCode() method for a cljc project
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require [tupelo.core :as t]) )
(defn str->hashcode
"Work-alike impl of Java String.hashCode() fn"
[str-val]
(let [char-codes (mapv int str-val)
step-fn (fn step-fn [hash-in char-code]
(let [hash-out (+ char-code
(-
(bit-shift-left hash-in 5)
hash-in))
hash-out (bit-and hash-out 0xFFFFFFFF)]
hash-out))
result (reduce step-fn 0 char-codes)]
result))
(dotest
(spy "hello")
(spyx (str->hashcode "hello"))
(spyx (.hashCode "hello"))
)
;-------------------------------
; Clojure 1.10.0 Java 12
;-------------------------------
;
; Testing tst.demo.core
; :spy => "hello"
; (str->hashcode "hello") => 99162322
; (.hashCode "hello") => 99162322
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment