Skip to content

Commit

Permalink
utils: add a hash function
Browse files Browse the repository at this point in the history
  • Loading branch information
Saviio committed Mar 23, 2017
1 parent 1e7cf0e commit 10b4d0a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/utils/hash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const hash = (str: string) => {
let ret = 0
for (let i = 0; i < str.length; i++) {
ret = ((ret << 5) - ret) + str.charCodeAt(i)
ret = ret & ret
}
return ret
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './hash'
export * from './clone'
export * from './valid'
export * from './option'
Expand Down
12 changes: 11 additions & 1 deletion test/specs/utils/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { forEach, clone, getType, assert } from '../../index'
import { forEach, clone, getType, assert, hash } from '../../index'
import { describe, it } from 'tman'
import { expect } from 'chai'

Expand Down Expand Up @@ -397,4 +397,14 @@ export default describe('Utils Testcase: ', () => {

})

describe('Func: hash', () => {

it('should be able to convert string to hash', () => {
expect(hash('')).to.equal(0)
expect(hash(' ')).to.equal(32)
expect(hash(' ')).to.equal(1024)
})

})

})

0 comments on commit 10b4d0a

Please sign in to comment.