String.hashCode
Implements a hashCode method to String prototype. Based on Java documentation.
by Ciul
HTML
<div>
<h3>String</h3>
<span id="input" contentEditable>Edit me!</span>
<span id="dohash">Click me</span>
</div>
<div>
<h3>Resulting hash</h3>
<span id="output">hash</span>
</div>
CSS
div {
border-radius: 2px;
border: 1px solid rgba(3,3,3,0.3);
margin: 8px;
padding: 4px;
}
h3 {
color: rgb(160,80,120);
font-weight: bold;
border-bottom: 1px dashed rgba(120, 40, 80, 0.3);
margin-bottom: 6px;
padding-bottom: 2px;
}
#input,
#output,
#dohash {
display: inline-block;
}
#input,
#output {
width: 100%;
min-height: 40px;
border: 1px solid black;
text-align: center;
font-weight: bold;
padding-top: 15px;
}
#dohash {
width: 100%;
height: 30px;
padding-top: 10px;
text-align: center;
color: #567;
text-shadow: 1px 1px #CCC;
background: rgba(100,100,100, 0.3);
cursor: pointer;
margin-top: 10px;
font-weight: bold;
}
#dohash:hover {
box-shadow: inset 0px 0px 6px black;
}
#dohash:active {
box-shadow: inset 0px 0px 4px 2px black;
}
#output {
width: 100%;
border: 1px solid black;
}
JavaScript
// Implements hashCode method to String prototype
String.implement('hashCode', function() {
var hash = 0, len = this.length;
if (this.length === 0) {
return hash;
}
for (i = 0; i < len; i++) {
charC = this.charCodeAt(i);
hash = ((hash<<5)-hash)+charC;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
});
$('dohash').addEvent('click', function () {
var input = $('input').getProperty('text');
var output = input.hashCode();
$('output').setProperty('text', output);
});