yanyue404/blog

小而美的工具为你的开发体验加分

Opened this issue · 0 comments

目录

1. 把数组格式化为对象
2. 遍历数组添加子项
3. 删除了某些字段的对象的浅拷贝
4. 返回对象白名单属性
5. 便于构建复杂的正则表达式
6. 精确地执行加,减,乘和除运算

array-to-hash-object

let before =  [
{
  id:1,
  name:"youngwind',
  age:24
},
{
 id:2,
 name:"xiaoye",
 age:30
}
];
var arrayToHash = require('array-to-hash-object');
var after = arrayToHash(before,'id');

// log after =>

/* {
  1: {
    name: 'youngwind',
    age: 24,
  },
  2: {
    name: 'xiaoye',
    age: 30,
  },
}; */

addkey

const addKey = require('addkey');
const moment = require('moment');
const toTime = (ctime) => moment(ctime * 1000).format('YYYY-MM-DD');

let arr = [
  {
    id: 1,
    name: '亚瑟',
    ctime: '1554863144',
  },
  {
    id: 2,
    name: '狄仁杰',
    ctime: '1557045386',
  },
  {
    id: 3,
    name: '曹操',
    ctime: '1548040191',
  },
];
addKey(arr, (v, index, array) => {
  v.time = toTime(v.ctime);
  delete v.ctime;
});

// log arr =>

/* [
  { id: 1, name: "亚瑟", time: "2019-04-10" },
  { id: 2, name: "狄仁杰", time: "2019-05-05" },
  { id: 3, name: "铠", time: "2019-01-21" }
]; */

omit

var omit = require('omit.js');
omit({ name: 'Benjy', age: 18 }, ['name']); // => { age: 18 }

only

var obj = {
  name: 'tobi',
  last: 'holowaychuk',
  email: 'tobi@learnboost.com',
  _id: '12345',
};

var user = only(obj, 'name last email'); // 或者 only(obj, ['name', 'last', 'email']);

// log user =>

/* {
  name: 'tobi',
  last: 'holowaychuk',
  email: 'tobi@learnboost.com'
} */

JSVerbalExpressions

// Create an example of how to test for correctly formed URLs
const tester = VerEx()
  .startOfLine()
  .then('http')
  .maybe('s')
  .then('://')
  .maybe('www.')
  .anythingBut(' ')
  .endOfLine();

// Create an example URL
const testMe = 'https://www.google.com';

// Use RegExp object's native test() function
if (tester.test(testMe)) {
  alert('We have a correct URL'); // This output will fire
} else {
  alert('The URL is incorrect');
}

console.log(tester); // Outputs the actual expression used: /^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$/

number-precision

1K 微小且快速的库,用于精确地执行加,减,乘和除运算

import NP from 'number-precision';
NP.strip(0.09999999999999998); // = 0.1
NP.plus(0.1, 0.2); // = 0.3, not 0.30000000000000004
NP.plus(2.3, 2.4); // = 4.7, not 4.699999999999999
NP.minus(1.0, 0.9); // = 0.1, not 0.09999999999999998
NP.times(3, 0.3); // = 0.9, not 0.8999999999999999
NP.times(0.362, 100); // = 36.2, not 36.199999999999996
NP.divide(1.21, 1.1); // = 1.1, not 1.0999999999999999
NP.round(0.105, 2); // = 0.11, not 0.1