# js-utils1 **Repository Path**: quoqingbo/js-utils1 ## Basic Information - **Project Name**: js-utils1 - **Description**: JavaScript 实用工具集。 - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 4 - **Created**: 2021-10-13 - **Last Updated**: 2021-10-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # js-utils 这里汇集了日常使用的 Javascript 实用工具,使用了 ES6 模块规范。 这些工具之间相互独立,可能有功能的重叠。 各实用工具的简介如下。 ## 表单验证器 [validator](./src/validator.js) 使用方法: ```js import { validate } from './src/validator.js'; // 原始数据,待校验 const raw = { type: '1', name: '123', }; // 自定义检验规则及提示语 const rules = [ { // 字段名 id: 'type', // 该字段名需要满足的规则 rules: [ { required: true, // 校验不通过时的提示语 msg: 'type is required', }, ], }, { id: 'name', rules: [ { required: true, msg: 'name is required' }, { // 过滤器,只有在某些条件下,才会开启这条规则 filter: (item) => item.type === '1', minlength: 6, msg: 'name too short', }, ], }, ]; // 校验结果 const expected = [ { id: 'type', ok: true }, { id: 'name', ok: false, msg: 'name too short' }, ]; expect(validate(raw, rules)).to.be.eql(expected); ``` 目前的规则有: - `required` 必填项 - `minlength` 最小长度 - `maxlength` 最大长度 - `phone` 必须满足手机号规则 - `idcard` 必须满足身份证号规则 - `regexp` 自定义正则表达式 - `func: (item, id, raw) => boolean` 自定义判定函数 ## [mergeUrl](./src/mergeUrl.js) 一个轻量级的页面参数拼接工具。使用方法如下: ```js const newUrl = mergeUrl('example.com?hello=world#foo', 'answer=42'); console.log(newUrl); // => 'example.com?hello=world&answer=42#foo' ``` ## [time](./src/time.js) 时间相关小工具,比如格式化日期输出: ```js const timestamp = '1589776171'; time.format('%y/%m/%d %h:%M:%s', timestamp); // => 2020/05/18 12:29:31 ``` 注意,为了方便与后端交互,time 中的所有时间戳都以秒为单位。 如果想知道两个时刻之间距离的天数,可以使用 `calculateDaysBetween(startTime, endTime)`: ```js import { calculateDaysBetween } from './time.js'; const startTime = 0; const endTime = 24 * 3600; calculateDaysBetween(startTime, endTime); // => 1 ``` 当知道某一时刻,想获取当天开始的时刻(即当天零时零分零秒),可以使用 `startOfDay()` 函数: ```js import { startOfDay } from './time.js'; // Tue Mar 02 2021 09:30:21 GMT+0800 (中国标准时间) const dayTime = 1614648621; // Tue Mar 02 2021 00:00:00 GMT+0800 (中国标准时间) const startOfDayTime = 1614614400; startOfDay(dayTime) === startOfDayTime; // => true ``` ## [parseQuery](./src/parseQuery.js) 解析 url 的页面参数,返回对应的对象格式。 ```js const url = 'http://example.com?foo=bar&answer=42#baz'; parseQuery(url); // { foo: 'bar', answer: '42' } ``` ## [stringifyQuery](./src/stringifyQuery.js) 将对象转换为页面参数的形式。 ```js stringifyQuery({ foo: 'bar', age: 42, }); // foo=bar&age=42 ``` ## [qsUtil](./src/qsUtil.js) qsUtil 是 **querystring util** 的简称,主要用来操作 URL 和页面参数。内置五个函数,分别是: 1. `update(url, params, config)` 使用 `params` 中的键值对更新 `url` 中的页面参数 2. `del(url, keys)` 删除 `url` 的某些页面参数,这些参数由 `keys` 指定 3. `parseURL(url)` 将 `url` 解析为 `path`、`search` 和 `hash` 三部分 4. `parseSearch(search)` 将页面参数 `search` 字符串解析为对象格式 5. `stringifySearch(params)` 将对象格式 `params` 拼接为页面参数 使用 `qsUtil.update(url, params, config)` 时,如果 `url` 的页面参数和 `params` 字段有冲突,可以设定 `config.override` 解决冲突。当且仅当 `config.override === false` 时,使用 `url` 的值,否则,使用 `params` 的值。 ```js const url = 'http://example.com?foo=1'; const params = { foo: 2, bar: 42 }; console.log(qsUtil.update(url, params)); // => http://example.com?foo=2&bar=42 const config = { override: false }; console.log(qsUtil.update(url, params, config)); // => http://example.com?foo=1&bar=42; ``` ## getValueAt `getValueAt(obj, path, defaultValue)` 模仿了 lodash 中 [`_.at(obj, [paths])`](https://lodash.com/docs/4.17.11#at) 的行为。但是这里的 `path` 只支持字符串格式,即每次只能获取一个数值。如果获取不到,可以设置默认值 `defaultValue`。 这个工具解决的问题模式如下: ```js const value = foo && foo.bar && foo.bar.hello && foo.bar.hello.world; ``` 当路径较深时,以上代码风格低效冗长。可以改为如下形式: ```js const value = getValueAt(foo, 'bar.hello.world'); ``` [源码](./src/getValueAt.js) ## [promisify](./src/promisify.js) `promisify()` 将 `success/fail` 风格的异步函数封装为 promise 风格的异步函数。 ```js function hello(params) { setTimeout(() => { const answer = Math.random(); if (answer >= 0.5) { params && params.success && params.success(answer); } else { params && params.fail && params.fail(answer); } }, 100); } promisify(hello)() .then((res) => { console.log(`:D ${res}`); }) .catch((err) => { console.log(`:( ${err}`); }); ``` ## [compareVersion](./src/compareVersion.js) `compareVersion` 用来比较版本的新旧,用法如下: ```js // 如果前者小于后者,返回 -1 compareVersion('1.0.0', '1.0.1'); // => -1 // 如果前者大于后者,返回 1 compareVersion('1.0.2', '1.0.1'); // => 1 // 如果前者等于后者,返回 0 compareVersion('1.0.1', '1.0.1'); // => 0 ``` ## [getRandomItem](./src/getRandomItem.js) `getRandomItem()` 可以从数组中随机选取一个元素。 ```js const item = getRandomItem([1, 2, 3, 4]); ``` ## [checkValid](./src/checkValid.js) `checkValid(params, cases)` 用于表单验证。其中: 1. `params`: 待校验的表单数据,是 `object` 类型 2. `cases`: 验证条件数组。每个条件的属性有:`key`, `required`, `phone`, `msg` 等 ```js const params = { name: 'Tony Stark', phone: 'wrong phone' }; const cases = [ { key: 'name', required: true, msg: 'name is required' }, { key: 'phone', required: true, msg: 'phone is required' }, { key: 'phone', phone: true, msg: 'invalid phone' }, ]; checkValid(params, cases); // => { valid: false, msg: 'invalid phone' } ```