UNPKG

2.18 kBPlain TextView Raw
1// from http://jsperf.com/hashing-strings
2export function hash(str: string){
3 let hashed = 0;
4 for (let ii = 0; ii < str.length; ii++) {
5 hashed = (31 * hashed + str.charCodeAt(ii)) | 0;
6 }
7 return smi(hashed);
8}
9
10export function toString(value: any) {
11 const type = typeof value;
12 if (type === "string") {
13 return value;
14 } else if (type === "number" || type === "boolean" || type === "function") {
15 return value.toString();
16 }
17 return JSON.stringify(value);
18}
19
20/**
21 * 默认比较函数
22 * @param a
23 * @param b
24 */
25export function defaultCompare<T>(a: T, b: T, key?: keyof T){
26 if (key){
27 return a[key] >= b[key];
28 }
29 return a >= b;
30}
31
32/**
33 * 默认比较函数
34 * a === b => 0,
35 * a > b => 1,
36 * a < b => -1,
37 * @param a
38 * @param b
39 * @returns number
40 */
41export function defaultEqualCompare<T>(a: T, b: T){
42 if (a === b) {
43 return 0;
44 }
45 return a > b ? 1 : -1;
46}
47
48/**
49 * 创建比较函数
50 * 1、<string>key => (a, b) => defaultCompare(a[key], b[key])
51 * 2、<function>key => key;
52 * 2、<undefined>key => defaultCompare
53 * @param key
54 */
55// export function createCompare<T>(key ?: IEqualCompare<T> | (keyof T)){
56// let compare = defaultEqualCompare as IEqualCompare<T>;
57// if (typeof key === "string") {
58// compare = (a, b) => defaultEqualCompare(a[key], b[key]);
59// }
60// if (typeof key === "function") {
61// compare = key;
62// }
63// return compare;
64// }
65
66/**
67 * 创建随机数
68 * @param begin 开始数值
69 * @param end 结束数值
70 */
71export function random(begin: number, end: number){
72 return Math.round(Math.random() * (end - begin) + begin);
73}
74
75/**
76 * 交换函数
77 * @param arr
78 * @param i
79 * @param j
80 */
81export function swap(arr: Array<any> , i: number , j: number){
82 const temp = arr[j];
83 arr[j] = arr[i];
84 arr[i] = temp;
85}
86
87// v8 has an optimization for storing 31-bit signed numbers.
88// Values which have either 00 or 11 as the high order bits qualify.
89// This function drops the highest order bit in a signed number, maintaining
90// the sign bit.
91function smi(i32: number) {
92 return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
93}