Skip to content

Commit 523e294

Browse files
author
xuezu
committed
add string.hashCode
1 parent 76509a3 commit 523e294

4 files changed

Lines changed: 76 additions & 0 deletions

File tree

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
node_modules
2+
logs
3+
test
4+
.*
5+
!.gitignore
6+
!.npmignore

.npmignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
test

index.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* - index.js
3+
* @author luckydrq([email protected])
4+
*/
5+
'use strict';
6+
7+
var util = require('core-util-is');
8+
9+
/**
10+
* return a hash code of this string
11+
* @ref http://blog.csdn.net/exceptional_derek/article/details/9074137
12+
* @param {String} str
13+
* @return {Number}
14+
* @api public
15+
*/
16+
exports.hashCode = function(str) {
17+
if (util.isFunction(str.hashCode)) {
18+
return str.hashCode();
19+
}
20+
21+
str = new String(str);
22+
str.value = str.split('').map(function(c) { return c.charCodeAt(0); });
23+
str.offset = 0;
24+
str.hash = 0;
25+
str.hashCode = function() {
26+
var count = this.length;
27+
var h = this.hash;
28+
if (h === 0 && count > 0) {
29+
var off = this.offset;
30+
var val = this.value;
31+
var len = count;
32+
for (var i = 0; i < len; i++) {
33+
h = 31 * h + val[off++];
34+
}
35+
this.hash = h;
36+
}
37+
return h;
38+
};
39+
return str.hashCode();
40+
};

package.json

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"name": "string-extras",
3+
"version": "0.0.1",
4+
"description": "Extra utilities for string",
5+
"keywords": [
6+
"string",
7+
"utility",
8+
"extra"
9+
],
10+
"maintainers": [
11+
{
12+
"name": "Deng Ruoqi",
13+
"email": "[email protected]"
14+
}
15+
],
16+
"scripts": {
17+
"test": "mocha ./test/*.test.js"
18+
},
19+
"repository": {
20+
"type": "git",
21+
"url": "[email protected]:luckydrq/string-extras.git"
22+
},
23+
"dependencies": {
24+
"core-util-is": "~1.0.1"
25+
},
26+
"devDependencies": {
27+
"mocha": "~2.2.5"
28+
}
29+
}

0 commit comments

Comments
 (0)