es6 數組的工具類

   根據Es6中map和Set的特性,實現了對array的分組和轉換操做。es6

   


exports.mapToObj = function (strMap) {
  let obj = Object.create(null);
  for (let [k,v] of strMap) {
    obj[k] = v;
  }
  return obj;
};

exports.objToMap = function (obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
};
exports.groupBy = function (values, key) {
  let map = new Map();
  for (let value of values) {
    if (!value.hasOwnProperty(key)) {
      return [];
    }
    let groupkey = value[key];
    let groupSet = map.get(groupkey) || new Set();
    groupSet.add(value);
    map.set(groupkey, groupSet);

  }
  return map;
};

exports.distinct=function (values) {
  if(!Array.isArray(values))
    throw new Error("invalid param");
  return [...new Set(values)];
};

如上,這樣利用es6的特性,不用再引入loadash等類庫,須要其餘功能都可方便的實現。spa

發句感慨,寫代碼就像作一件藝術品,要有所追求,不要草草了事,有匠心也有意思。code

相關文章
相關標籤/搜索