一些工具函数集合

判断一个值是数组或者是类数组

1
function _isLength(value) {
2
  return typeof value == 'number' &&
3
         value > -1 &&
4
         value % 1 = 0 &&
5
         value <= Number.MAX_SAFE_INTEGER
6
}
7
function _isArray(value) {
8
  return typeof value != null &&
9
         _isLength(value.length) && 
10
         typeof value != 'function' 
11
}

操作对象的工具函数

1
Object.keys(object) -> 返回包含 key 的数组
2
Object.values(object) -> 返回 包含 value 的数组

找出所有大于2小于1024的2的倍数

1
function iterateUntil(compute, checker, init) {
2
  let ret = [];
3
  let result = compute(init);
4
  while(checker(result)) {
5
    ret.push(result);
6
    result = compute(result);
7
  }
8
  return ret;
9
}
10
11
iterateUntil(function(n) {
12
  return n + n;
13
}, function(n) {
14
  return n <= 1024;
15
}, 1)
16
17
// [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

深拷贝函数

1
function find (list, f) {
2
  return list.filter(f)[0]
3
}
4
5
function deepCopy (obj, cache = []) {
6
  // just return if obj is immutable value
7
  if (obj === null || typeof obj !== 'object') {
8
    return obj
9
  }
10
11
  // if obj is hit, it is in circular structure
12
  const hit = find(cache, c => c.original === obj)
13
  if (hit) {
14
    return hit.copy
15
  }
16
17
  const copy = Array.isArray(obj) ? [] : {}
18
  // put the copy into cache at first
19
  // because we want to refer it in recursive deepCopy
20
  cache.push({
21
    original: obj,
22
    copy
23
  })
24
25
  Object.keys(obj).forEach(key => {
26
    copy[key] = deepCopy(obj[key], cache)
27
  })
28
29
  return copy
30
}

如何判断一个函数是 Promise 类型?

1
function isPromise(val) {
2
    return val && typeof val.then === 'function'
3
}