今天介绍几个比较实用javasscript 工具函数,如下:
is-empty 判断数组是否为空

function isEmpty(thing) {
  return !thing || thing.length < 1 || !Object.keys(thing).length;
}

使用如下:

 *      isEmpty() // => true
 *      isEmpty([]) // => true
 *      isEmpty({}) // => true
 *      isEmpty('') // => true
 *      isEmpty([8, 9, 6]) // => false
 *      isEmpty('text') // => false
 *      isEmpty({a: 1}) // => false

hasDuplicates 判断数组是否有重复值

function hasDuplicates(array) {
  const words = new Map();
  for (let index = 0; index < array.length; index++) {
    const word = array[index];
    if (words.has(word)) {
      return true;
    }
    words.set(word, true);
  }
  return false;
}

使用如下:

 *    hasDuplicates([]); //↪️ false
 *    hasDuplicates([1, 1]); //↪️ true
 *    hasDuplicates([1, 2]); //↪️ false

merge 方法 merge两个数组并且升序排序

function merge(a = [], b = []) {
  const merged = [];
  // merge elements on a and b in asc order. Run-time O(a + b)
  for (let ai = 0, bi = 0; ai < a.length || bi < b.length;) {
    if (ai >= a.length || a[ai] > b[bi]) {
      merged.push(b[bi++]);
    } else {
      merged.push(a[ai++]);
    }
  }
  return merged;
}

使用如下:
merge([2,5,9], [1,6,7]) => [1, 2, 5, 6, 7, 9]

findSubsets 返回一个集合的所有子集

function findSubsets(n = '') {
  const array = Array.from(n);
  const base = ['']; // <1>

  const results = array.reduce((previous, element) => {
    const previousPlusElement = previous.map((el) => `${el}${element}`); // <2>
    return previous.concat(previousPlusElement); // <3>
  }, base);

  return results;
}

使用如下:

 *    findSubsets('a') //↪️ ['', 'a']
 *    findSubsets([1, 'b']) //↪️ ['', '1', 'b', '1b']
 *    findSubsets('abc') //↪️ ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']

getPermutations 查找单词可能具有的所有不同排列

function getPermutations(word = '', prefix = '') {
  if (word.length <= 1) {
    return [prefix + word];
  }
  return Array.from(word).reduce((result, char, index) => {
    const reminder = word.slice(0, index) + word.slice(index + 1);
    return result.concat(getPermutations(reminder, prefix + char));
  }, []);
}

使用如下:

 *    getPermutations('a') => ['a']
 *    getPermutations('ab') => ['ab', 'ba']
 *    getPermutations('mad') => ['mad', 'mda', 'amd', 'adm', 'dma', 'dam']

henry_57bcfc6a67f76
1 声望0 粉丝