ph-utils 0.2.23 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/web.js CHANGED
@@ -1,141 +1,57 @@
1
- /**
2
- * web(浏览器) 端工具类
3
- */
4
- import { isBlank } from './index_m';
5
- /**
6
- * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
7
- * @param form {object} Form 节点对象
8
- */
9
- export const formJson = function (form) {
10
- let elems = form.elements;
11
- let value = {};
12
- for (let i = 0, len = elems.length; i < len; i++) {
13
- let item = elems[i];
14
- if (!isBlank(item.name)) {
15
- if ((item.tagName === 'INPUT' || item.tagName === 'TEXTAREA') &&
16
- !isBlank(item.value)) {
17
- let dataType = item.getAttribute('data-type');
18
- if (dataType === 'number') {
19
- value[item.name] = Number(item.value);
20
- }
21
- else {
22
- value[item.name] = item.value;
23
- }
24
- }
25
- else if (item.tagName === 'SELECT') {
26
- value[item.name] = item.options[item.selectedIndex].value;
27
- }
28
- }
29
- }
30
- return value;
31
- };
32
- /**
33
- * 获取 url query 参数 (get 请求的参数)
34
- * @param search 如果是 React 应用就需要传递 useLocation().search
35
- * @returns
36
- */
37
- export function query(search) {
38
- if (isBlank(search)) {
39
- search = location.search;
40
- }
41
- const searchParams = new URLSearchParams(search);
42
- let query = {};
43
- for (const [key, value] of searchParams) {
44
- let oldValue = query[key];
45
- let newValue = value;
46
- if (oldValue != null) {
47
- if (oldValue instanceof Array) {
48
- oldValue.push(value);
49
- newValue = oldValue;
50
- }
51
- else {
52
- newValue = [value, oldValue];
53
- }
54
- }
55
- query[key] = newValue;
56
- }
57
- return query;
58
- }
59
- export function random() {
60
- let r = Math.random();
61
- const startOrLen = arguments[0];
62
- let endOrFirstZero = arguments[1];
63
- if (typeof endOrFirstZero === 'number') {
64
- /* 生成两个数字之间的随机数(number) */
65
- let opts = arguments[3];
66
- const dftOpts = { isInt: true };
67
- opts = Object.assign(dftOpts, opts || {});
68
- const e = opts.isInt && opts.hasEnd ? 1 : 0;
69
- const rs = r * (endOrFirstZero - startOrLen + e) + startOrLen;
70
- return opts.isInt ? parseInt(rs, 10) : rs;
71
- }
72
- endOrFirstZero = endOrFirstZero || true;
73
- if (endOrFirstZero) {
74
- // 生成的数字包含前面的0
75
- r = r.toString();
76
- return r.substr(r.indexOf('.') + 1, startOrLen);
77
- }
78
- const max = Math.pow(10, startOrLen - 1);
79
- r = parseInt(String(r * max), 10);
80
- if (r < max) {
81
- // 生成的随机数前置有0,重新生成随机数
82
- return random(startOrLen, endOrFirstZero);
83
- }
84
- return r;
85
- }
86
- /**
87
- * 将金额数字格式化为金额格式显示并且会保留两位小数[去除多余的位数,不是四舍五入,而是直接舍去] 1234523432.23 => 123,123,123.23
88
- * @param {number} number 待转换的金额数字
89
- * @return string
90
- */
91
- export function formatMoney(number) {
92
- number = number || 0;
93
- let negative = '';
94
- let base = String(parseInt(number, 10)); // 获取数字整数部分
95
- let mod = base.length > 3 ? base.length % 3 : 0;
96
- /*
97
- * 利用 正则前瞻 (?=) 将3位数字后面还紧跟一位数字的三位数字替换为 数字, 的形式
98
- */
99
- let numberStr = String(number);
100
- let usePrecision = numberStr.indexOf('.');
101
- let dotStr = usePrecision > 0 ? numberStr.slice(usePrecision + 1) : '00';
102
- dotStr = dotStr.length > 2 ? dotStr.slice(0, 2) : dotStr;
103
- return (negative +
104
- (mod ? base.slice(0, mod) + ',' : '') +
105
- base.slice(mod).replace(/(\d{3})(?=\d)/g, '$1,') +
106
- '.' +
107
- dotStr);
108
- }
109
- /**
110
- * 函数节流 - 每隔单位时间,只执行一次
111
- * @param cb 待节流的函数
112
- * @param wait 间隔时间
113
- * @returns
114
- */
115
- export function throttle(fn, wait = 500) {
116
- // 上一次的请求时间
117
- let last = 0;
118
- return (...args) => {
119
- // 当前时间戳
120
- const now = Date.now();
121
- if (now - last > wait) {
122
- fn(...args);
123
- last = now;
124
- }
125
- };
126
- }
127
- /**
128
- * 函数防抖 - 当重复触发某一个行为(事件时),只执行最后一次触发
129
- * @param fn 防抖函数
130
- * @param interval 间隔时间段
131
- * @returns
132
- */
133
- export function debounce(fn, interval = 500) {
134
- let _t = -1;
135
- return (...args) => {
136
- clearTimeout(_t);
137
- _t = setTimeout(() => {
138
- fn(...args);
139
- }, interval);
140
- };
141
- }
1
+ /**
2
+ * web(浏览器) 端工具类
3
+ */
4
+ import { isBlank } from './index';
5
+ /**
6
+ * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
7
+ * @param form {object} Form 节点对象
8
+ */
9
+ export const formJson = function (form) {
10
+ let elems = form.elements;
11
+ let value = {};
12
+ for (let i = 0, len = elems.length; i < len; i++) {
13
+ let item = elems[i];
14
+ if (!isBlank(item.name)) {
15
+ if ((item.tagName === 'INPUT' || item.tagName === 'TEXTAREA') && !isBlank(item.value)) {
16
+ let dataType = item.getAttribute('data-type');
17
+ if (dataType === 'number') {
18
+ value[item.name] = Number(item.value);
19
+ }
20
+ else {
21
+ value[item.name] = item.value;
22
+ }
23
+ }
24
+ else if (item.tagName === 'SELECT') {
25
+ value[item.name] = item.options[item.selectedIndex].value;
26
+ }
27
+ }
28
+ }
29
+ return value;
30
+ };
31
+ /**
32
+ * 获取 url query 参数 (get 请求的参数)
33
+ * @param search 如果是 React 应用就需要传递 useLocation().search
34
+ * @returns
35
+ */
36
+ export function query(search) {
37
+ if (isBlank(search)) {
38
+ search = location.search;
39
+ }
40
+ const searchParams = new URLSearchParams(search);
41
+ let query = {};
42
+ for (const [key, value] of searchParams) {
43
+ let oldValue = query[key];
44
+ let newValue = value;
45
+ if (oldValue != null) {
46
+ if (oldValue instanceof Array) {
47
+ oldValue.push(value);
48
+ newValue = oldValue;
49
+ }
50
+ else {
51
+ newValue = [value, oldValue];
52
+ }
53
+ }
54
+ query[key] = newValue;
55
+ }
56
+ return query;
57
+ }
package/package.json CHANGED
@@ -2,10 +2,11 @@
2
2
  "name": "ph-utils",
3
3
  "description": "js 开发工具集,前后端都可以使用(commonjs和es module)",
4
4
  "main": "lib/index.js",
5
- "module": "lib/index_m.js",
5
+ "module": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
7
- "browser": "lib/index_m.js",
8
- "version": "0.2.23",
7
+ "browser": "lib/index.js",
8
+ "version": "0.3.1",
9
+ "type": "module",
9
10
  "repository": {
10
11
  "type": "git",
11
12
  "url": "git+https//gitee.com/towardly/ph.git",
@@ -18,11 +19,8 @@
18
19
  },
19
20
  "homepage": "https://gitee.com/towardly/ph/tree/master/packages/utils",
20
21
  "devDependencies": {
21
- "@types/node": "^17.0.21",
22
- "typescript": "4.5.5"
23
- },
24
- "scripts": {
25
- "build": "node scripts/build.js"
22
+ "@types/node": "^20.3.1",
23
+ "typescript": "^5.1.3"
26
24
  },
27
25
  "files": [
28
26
  "lib"
@@ -34,5 +32,8 @@
34
32
  "date",
35
33
  "dom",
36
34
  "file"
37
- ]
35
+ ],
36
+ "scripts": {
37
+ "build": "node scripts/build.js"
38
+ }
38
39
  }
package/lib/date_m.d.ts DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * 将日期格式化为指定形式的字符串
3
- * @param date 日期
4
- * @param pattern 格式化字符串 yyyy - 年, mm - 月, dd - 日, HH - 小时, MM - 分钟, ss - 秒
5
- */
6
- export declare function format(date?: Date | string | number, pattern?: string): string;
7
- /**
8
- * 将指定的参数解析为日期对象(Date)
9
- * 参考 dayjs 实现, 也可以参考 https://github.com/nomiddlename/date-format
10
- * @param date 待解析的日期参数
11
- */
12
- export declare function parse(date?: Date | string | number): Date;
13
- /**
14
- * 设置日期的开始或者结束的点
15
- * @param {Object} date 日期,能够被 parse 解析的日期
16
- * @param {String} unit 单位,H Hours, 默认为 H
17
- * @param {Boolean} isEnd true则为 endOf
18
- */
19
- export declare function startOf(date?: Date | string | number, unit?: string, isEnd?: boolean): Date;
20
- /**
21
- * 日期加上指定时间后的日期
22
- * @param date 指定的日期
23
- * @param num 需要添加的数字, 如果这个参数传递一个小于0的数字,则就是日期减去相应的数字
24
- * @param unit 需要添加的单位,date - 加减天数
25
- */
26
- export declare function add(date: Date | string | number | null, num: number, unit: string): Date;
27
- /**
28
- * 日期加上指定时间后的日期
29
- * @param date 指定的日期, 传递为 null ,则表示为当前日期
30
- * @param num 需要添加的数字, 如果这个参数传递一个小于0的数字,则就是日期减去相应的数字
31
- * @param unit 需要添加的单位,date - 加减天数
32
- * @param fmt 如果传递了格式化的单位,则返回格式化后的日期, 格式化字符串 yyyy - 年, mm - 月, dd - 日, HH - 小时, MM - 分钟, ss - 秒
33
- */
34
- export declare function add(date: Date | string | number | null, num: number, unit: string, fmt: string): string;
package/lib/date_m.js DELETED
@@ -1,119 +0,0 @@
1
- /**
2
- * node 和 web 端日期处理工具类
3
- */
4
- // 配置日期格式的正则表达式
5
- const REGEX_FORMAT = /yy(?:yy)?|([HMmds])\1?/g;
6
- // 由于 Date.parse() 不能正确解析 yyyy-dd-mm 格式的日期, 所以匹配手动解析
7
- const REGEX_PARSE = /^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/;
8
- /**
9
- * 不足位数, 前位补 0
10
- * @param s 日期数字
11
- * @param l 截取位数
12
- * @returns {string} 补0后的日期数字
13
- */
14
- function p(s, l = 2) {
15
- /*
16
- * 由于年份最多为4为,所以前面先添3个0
17
- * slice() 从后开始提前字符串
18
- */
19
- return ('000' + s).slice(l * -1);
20
- }
21
- function getUnit(unit) {
22
- return unit.substring(0, 1).toUpperCase() + unit.substring(1);
23
- }
24
- /**
25
- * 将日期格式化为指定形式的字符串
26
- * @param date 日期
27
- * @param pattern 格式化字符串 yyyy - 年, mm - 月, dd - 日, HH - 小时, MM - 分钟, ss - 秒
28
- */
29
- export function format(date, pattern = 'yyyy-mm-dd HH:MM') {
30
- date = parse(date);
31
- let d = date.getDate();
32
- let y = date.getFullYear();
33
- let m = date.getMonth();
34
- let H = date.getHours();
35
- let M = date.getMinutes();
36
- let s = date.getSeconds();
37
- let flags = {
38
- yy: p(y),
39
- yyyy: y,
40
- m: m + 1,
41
- mm: p(m + 1),
42
- d: d,
43
- dd: p(d),
44
- H: H,
45
- HH: p(H),
46
- M: M,
47
- MM: p(M),
48
- s: s,
49
- ss: p(s),
50
- };
51
- if (pattern != null) {
52
- return pattern.replace(REGEX_FORMAT, (flag) => {
53
- if (flag in flags) {
54
- return flags[flag];
55
- }
56
- return flag;
57
- });
58
- }
59
- return String(date.getTime());
60
- }
61
- /**
62
- * 将指定的参数解析为日期对象(Date)
63
- * 参考 dayjs 实现, 也可以参考 https://github.com/nomiddlename/date-format
64
- * @param date 待解析的日期参数
65
- */
66
- export function parse(date) {
67
- if (date == null)
68
- return new Date();
69
- if (date instanceof Date)
70
- return date;
71
- if (typeof date === 'string' && !/Z$/i.test(date)) {
72
- const d = date.match(REGEX_PARSE);
73
- if (d) {
74
- return new Date(d[1], d[2] - 1, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0);
75
- }
76
- }
77
- return new Date(date);
78
- }
79
- /**
80
- * 设置日期的开始或者结束的点
81
- * @param {Object} date 日期,能够被 parse 解析的日期
82
- * @param {String} unit 单位,H Hours, 默认为 H
83
- * @param {Boolean} isEnd true则为 endOf
84
- */
85
- export function startOf(date, unit, isEnd = false) {
86
- const argumentStart = [0, 0, 0, 0];
87
- const argumentEnd = [23, 59, 59, 999];
88
- date = parse(date);
89
- let u = getUnit(unit || 'Hours');
90
- let fn = 'set' + u;
91
- let args = isEnd === true ? argumentEnd : argumentStart;
92
- Date.prototype[fn].apply(date, args);
93
- return date;
94
- }
95
- /**
96
- * 日期加上指定时间后的日期
97
- * @param date 指定的日期
98
- * @param num 需要添加的数字, 如果这个参数传递一个小于0的数字,则就是日期减去相应的数字
99
- * @param unit 需要添加的单位,date - 加减天数
100
- * @param fmt 可选参数,如果传递了格式化的单位,则返回格式化后的日期, 格式化字符串 yyyy - 年, mm - 月, dd - 日, HH - 小时, MM - 分钟, ss - 秒
101
- * @returns {Date | string} 如果传递了 fmt 参数,则返回 string,否则返回 Date
102
- */
103
- export function add(date, num, unit, fmt) {
104
- let sdate = new Date();
105
- if (date != null) {
106
- sdate = parse(date);
107
- }
108
- unit = getUnit(unit);
109
- let fn = 'set' + unit;
110
- let gn = 'get' + unit;
111
- let oldValue = Date.prototype[gn].apply(sdate);
112
- Date.prototype[fn].apply(sdate, [oldValue + num]);
113
- if (typeof fmt === 'string') {
114
- return format(sdate, fmt);
115
- }
116
- else {
117
- return sdate;
118
- }
119
- }
package/lib/index_m.d.ts DELETED
@@ -1,61 +0,0 @@
1
- /**
2
- * node 和 web 通用的工具类
3
- */
4
- /**
5
- * 验证字符串是否为空
6
- * @param str 待验证的字符串
7
- * @param ignoreWhitespace 是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
8
- */
9
- export declare function isBlank(str?: string | null, ignoreWhitespace?: boolean): boolean;
10
- /**
11
- * 屏蔽手机号,中间部分用 * 展示
12
- * @param mobile 待屏蔽的手机号
13
- * @returns 屏蔽后的手机号,例如:123 **** 1234
14
- */
15
- export declare function shieldMobile(mobile: string): string;
16
- /**
17
- * 验证参数是否是数字
18
- * @param str 待验证的字符串
19
- * @param numericParam 通过参数标记是否包含小数、正数
20
- * @param numericParam.isPositive 是否是正数
21
- * @param numericParam.isFloat 是否是小数
22
- * @returns true 是数字, false 不是数字
23
- */
24
- export declare function isNumeric(str: string, numericParam?: {
25
- isPositive?: boolean;
26
- isFloat?: boolean;
27
- }): boolean;
28
- /**
29
- * 验证参数是否是Boolean 类型
30
- * @param str 待验证的字符串
31
- * @returns
32
- */
33
- export declare function isBoolean(str: string): boolean;
34
- /**
35
- * 带有错误名称标记的错误类型
36
- */
37
- export declare class BaseError extends Error {
38
- /**
39
- * 错误名称,类似于 Java 中的不同的 Exception[NullPointerException];
40
- * 增加 name 字段,表明不同的错误,当需要根据不同的错误执行不同的处理的时候,会很有用
41
- */
42
- name: string;
43
- /**
44
- * 构造一个 name = BaseError 的错误信息
45
- * @param message 错误描述
46
- */
47
- constructor(message: string);
48
- /**
49
- *
50
- * @param name 错误名称
51
- * @param message 错误描述
52
- */
53
- constructor(name: string, message: string);
54
- }
55
- /**
56
- * 创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。
57
- * @param func 要节流的函数
58
- * @param wait 需要节流的毫秒
59
- * @returns
60
- */
61
- export declare function throttle<T extends (...args: any) => any>(func: T, wait?: number): (...args: any[]) => void;
package/lib/index_m.js DELETED
@@ -1,82 +0,0 @@
1
- /**
2
- * node 和 web 通用的工具类
3
- */
4
- /**
5
- * 验证字符串是否为空
6
- * @param str 待验证的字符串
7
- * @param ignoreWhitespace 是否忽略空格(包括空白字符串以及[\r\t\n]之类的制表符),默认为true
8
- */
9
- export function isBlank(str, ignoreWhitespace = true) {
10
- if (str == null) {
11
- return true;
12
- }
13
- return (ignoreWhitespace ? str.trim().length : str.length) === 0;
14
- }
15
- /**
16
- * 屏蔽手机号,中间部分用 * 展示
17
- * @param mobile 待屏蔽的手机号
18
- * @returns 屏蔽后的手机号,例如:123 **** 1234
19
- */
20
- export function shieldMobile(mobile) {
21
- let x1 = Math.floor(mobile.length / 2);
22
- let x2 = Math.ceil(x1 / 2);
23
- let shields = [' '];
24
- for (let i = 0; i < x1 - 1; i++) {
25
- shields.push('*');
26
- }
27
- shields.push(' ');
28
- return (mobile.substring(0, x2) + shields.join('') + mobile.substring(x2 + x1 - 1));
29
- }
30
- /**
31
- * 验证参数是否是数字
32
- * @param str 待验证的字符串
33
- * @param numericParam 通过参数标记是否包含小数、正数
34
- * @param numericParam.isPositive 是否是正数
35
- * @param numericParam.isFloat 是否是小数
36
- * @returns true 是数字, false 不是数字
37
- */
38
- export function isNumeric(str, numericParam) {
39
- numericParam = { isPositive: false, isFloat: true, ...(numericParam || {}) };
40
- let symbol = numericParam.isPositive ? '[+]?' : '[+-]?';
41
- let main = numericParam.isFloat ? '([0-9]*[.])?[0-9]+' : '[0-9]+';
42
- return new RegExp('^' + symbol + main + '$').test(str);
43
- }
44
- /**
45
- * 验证参数是否是Boolean 类型
46
- * @param str 待验证的字符串
47
- * @returns
48
- */
49
- export function isBoolean(str) {
50
- return ['true', 'false'].indexOf(str) >= 0;
51
- }
52
- /**
53
- * 带有错误名称标记的错误类型
54
- */
55
- export class BaseError extends Error {
56
- constructor() {
57
- if (arguments.length === 1) {
58
- super(arguments[0]);
59
- this.name = 'BaseError';
60
- }
61
- else {
62
- super(arguments[1]);
63
- this.name = arguments[0];
64
- }
65
- }
66
- }
67
- /**
68
- * 创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。
69
- * @param func 要节流的函数
70
- * @param wait 需要节流的毫秒
71
- * @returns
72
- */
73
- export function throttle(func, wait = 300) {
74
- let t = -1;
75
- return function (...args) {
76
- const self = this;
77
- clearTimeout(t);
78
- t = setTimeout(() => {
79
- func.apply(self, args);
80
- }, wait);
81
- };
82
- }
@@ -1,47 +0,0 @@
1
- /**
2
- * 数据验证器
3
- */
4
- interface RuleItem {
5
- rule: RegExp | ((v: any) => boolean) | 'required';
6
- message: string;
7
- sameKey?: string;
8
- }
9
- export declare type RuleType = string | RegExp | ((v: any) => boolean) | (RegExp | string | ((v: any) => boolean) | {
10
- rule: string | RegExp | ((v: any) => boolean);
11
- message?: string;
12
- });
13
- export interface SchemaType {
14
- key: string;
15
- required?: boolean;
16
- type?: string | ((v: any) => void);
17
- rules: RuleType[];
18
- message?: string;
19
- }
20
- /**
21
- * 数据验证器,除了进行数据验证外,还可以同时进行数据转化
22
- */
23
- declare class Validator {
24
- rules: {
25
- [index: string]: RuleItem[];
26
- };
27
- /**
28
- * 构造数据验证转换器
29
- * @param schemas 配置验证转换规则
30
- */
31
- constructor(schemas: SchemaType[]);
32
- /**
33
- * 进行数据验证
34
- * @param data 待验证的数据
35
- * @returns
36
- */
37
- validate(data: any): Promise<boolean>;
38
- /**
39
- * 只验证指定 key 的数据格式
40
- * @param key 指定待验证的 key
41
- * @param value 待验证的数据
42
- */
43
- validateKey(key: string, value: any, data?: any): Promise<boolean>;
44
- private _validateRule;
45
- private _parseStringRule;
46
- }
47
- export default Validator;