@polyv/utils 1.5.1 → 2.0.0-beta.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.
Files changed (56) hide show
  1. package/README.md +33 -18
  2. package/dist/cjs/boolean.d.ts +45 -0
  3. package/dist/cjs/boolean.js +1 -0
  4. package/dist/cjs/countdown.d.ts +97 -0
  5. package/dist/cjs/countdown.js +1 -0
  6. package/dist/cjs/date.d.ts +44 -0
  7. package/dist/cjs/date.js +1 -0
  8. package/dist/cjs/json.d.ts +43 -0
  9. package/dist/cjs/json.js +1 -0
  10. package/dist/cjs/net.d.ts +32 -0
  11. package/dist/cjs/net.js +1 -0
  12. package/dist/cjs/string.d.ts +94 -0
  13. package/dist/cjs/string.js +1 -0
  14. package/dist/cjs/validate.d.ts +26 -0
  15. package/dist/cjs/validate.js +1 -0
  16. package/dist/es/boolean.d.ts +45 -0
  17. package/dist/es/boolean.js +1 -0
  18. package/dist/es/countdown.d.ts +97 -0
  19. package/dist/es/countdown.js +1 -0
  20. package/dist/es/date.d.ts +44 -0
  21. package/dist/es/date.js +1 -0
  22. package/dist/es/json.d.ts +43 -0
  23. package/dist/es/json.js +1 -0
  24. package/dist/es/net.d.ts +32 -0
  25. package/dist/es/net.js +1 -0
  26. package/dist/es/string.d.ts +94 -0
  27. package/dist/es/string.js +1 -0
  28. package/dist/es/validate.d.ts +26 -0
  29. package/dist/es/validate.js +1 -0
  30. package/package.json +31 -26
  31. package/dist/boolean.js +0 -1
  32. package/dist/browser.js +0 -1
  33. package/dist/cookie.js +0 -1
  34. package/dist/countdown.js +0 -1
  35. package/dist/date.js +0 -1
  36. package/dist/lang.js +0 -1
  37. package/dist/net.js +0 -1
  38. package/dist/polling.js +0 -1
  39. package/dist/querystring.js +0 -1
  40. package/dist/storage.js +0 -1
  41. package/dist/string.js +0 -1
  42. package/dist/validate.js +0 -1
  43. package/src/boolean.js +0 -67
  44. package/src/browser.js +0 -81
  45. package/src/cookie.js +0 -115
  46. package/src/countdown.js +0 -91
  47. package/src/date.js +0 -92
  48. package/src/internal/core.js +0 -59
  49. package/src/internal/timeunit.js +0 -63
  50. package/src/lang.js +0 -120
  51. package/src/net.js +0 -54
  52. package/src/polling.js +0 -142
  53. package/src/querystring.js +0 -121
  54. package/src/storage.js +0 -106
  55. package/src/string.js +0 -105
  56. package/src/validate.js +0 -42
package/src/polling.js DELETED
@@ -1,142 +0,0 @@
1
- /**
2
- * 本模块提供轮询功能。
3
- * @module polling
4
- */
5
-
6
- import { theGlobal } from './internal/core';
7
- import { extend } from './lang';
8
-
9
- /**
10
- * 轮询类。
11
- * @memberof module:polling
12
- * @class
13
- * @name Polling
14
- * @constructor
15
- * @param {Function} executor 执行函数,返回值为 Promise(带有 then 方法)时会进行异步处理。
16
- * @param {Object} [options] 其他选项。
17
- * @param {number} [options.interval=1000] 轮询间隔(毫秒)。
18
- * @param {boolean} [options.breakOnError=false] 执行函数有异常(包括 Promise 的拒绝状态)时是否中断轮询。
19
- * @example
20
- * const polling = new Polling(() => {
21
- * return new Promise((resolve) => {
22
- * setTimeout(() => {
23
- * console.log('executed');
24
- * resolve();
25
- * }, 1000);
26
- * });
27
- * }, {
28
- * interval: 2000
29
- * });
30
- * polling.start();
31
- */
32
- export default class Polling {
33
- constructor(executor, options) {
34
- // 执行函数
35
- this._executor = executor;
36
- // 其他选项
37
- this._options = extend({
38
- interval: 1000,
39
- breakOnError: false
40
- }, options);
41
- // 轮询计时器 id
42
- this._timerId = null;
43
- // 轮询是否已开始
44
- this._started = false;
45
- // 是否正在运行执行函数(针对异步情况)
46
- this._isExecuting = false;
47
- // 是否要在当前轮询之后马上运行执行函数
48
- this._shouldImmediate = false;
49
- }
50
-
51
- // 执行轮询函数
52
- _exec() {
53
- let result;
54
- try {
55
- result = this._executor.call(theGlobal);
56
- } catch (e) {
57
- if (this._options.breakOnError) {
58
- this.stop();
59
- }
60
- }
61
-
62
- if (result && typeof result.then === 'function') {
63
- // 异步情况,在 Promise 回调中继续下一次轮询
64
- this._isExecuting = true;
65
- result.then(() => {
66
- this._isExecuting = false;
67
- this._next();
68
- }, () => {
69
- this._isExecuting = false;
70
- if (this._options.breakOnError) {
71
- this.stop();
72
- } else {
73
- this._next();
74
- }
75
- });
76
-
77
- } else {
78
- // 同步情况,直接执行下一次轮询
79
- this._next();
80
- }
81
- }
82
-
83
- // 下一次轮询
84
- _next() {
85
- if (this._shouldImmediate) {
86
- // 外部调用了 execImmediately,马上执行
87
- this._exec();
88
-
89
- } else if (this._started) {
90
- // 进入下一次轮询
91
- this._timerId = setTimeout(() => {
92
- this._exec();
93
- }, this._options.interval);
94
- }
95
- }
96
-
97
- /**
98
- * 在当前轮询结束后马上执行一次执行函数。
99
- * @method
100
- * @memberof module:polling.Polling.prototype
101
- */
102
- execImmediately() {
103
- // 阻止下次轮询
104
- this._clearTimeout();
105
-
106
- if (this._isExecuting) {
107
- // 如果当前轮询还在运行中,先记录下来,待结束后再执行
108
- this._shouldImmediate = true;
109
- } else {
110
- // 下一次轮询还没开始,直接运行执行函数
111
- this._exec();
112
- }
113
- }
114
-
115
- /**
116
- * 启动轮询。
117
- * @method
118
- * @memberof module:polling.Polling.prototype
119
- */
120
- start() {
121
- this._started = true;
122
- this._exec();
123
- }
124
-
125
- /**
126
- * 停止轮询。
127
- * @method
128
- * @memberof module:polling.Polling.prototype
129
- */
130
- stop() {
131
- this._clearTimeout();
132
- this._started = false;
133
- }
134
-
135
- // 清理计时器
136
- _clearTimeout() {
137
- if (this._timerId) {
138
- clearTimeout(this._timerId);
139
- this._timerId = null;
140
- }
141
- }
142
- }
@@ -1,121 +0,0 @@
1
- /**
2
- * 本模块提供 URL 查询字符串的操作方法。
3
- * @module querystring
4
- */
5
-
6
- import { hasOwnProp } from './lang';
7
-
8
- /**
9
- * 把查询字符串反序列化为键值对集合。
10
- * @author luoliquan
11
- * @param {string} str 查询字符串。
12
- * @return {Object} 键值对集合。
13
- * @example
14
- * parse('a=1&%E9%94%AE=%E5%80%BC'); // { a: 1, '键': '值' }
15
- * parse('a=1&a=2&b=3'); // { a: [1, 2], b: 3 }
16
- */
17
- export function parse(str) {
18
- if (typeof str !== 'string') {
19
- throw new Error('The str argument must be a string type');
20
- }
21
-
22
- const result = {};
23
-
24
- str.split('&').forEach(function(pair) {
25
- if (!pair) { return; }
26
- pair = pair.split('=');
27
- const key = decodeURIComponent(pair[0]);
28
- const value = decodeURIComponent(pair[1] || '');
29
-
30
- if (hasOwnProp(result, key)) {
31
- // 出现重复 key 值时解析为数组
32
- if (!Array.isArray(result[key])) {
33
- result[key] = [result[key]];
34
- }
35
- result[key].push(value);
36
- } else {
37
- result[key] = value;
38
- }
39
- });
40
-
41
- return result;
42
- }
43
-
44
- /**
45
- * 把键值对集合序列化为查询字符串。
46
- * @author luoliquan
47
- * @param {Object} data 键值对集合。
48
- * @param {Object} [options] 参数。
49
- * @param {Boolean} [options.ignoreEmpty=false] 是否忽略空值(包括null、undefined、空字符串)。
50
- * @return {string} 序列化结果。
51
- * @example
52
- * stringify({ a: 1, '键': '值' }); // 'a=1&%E9%94%AE=%E5%80%BC'
53
- * stringify({ a: [1, 2], b: 3 }); // 'a=1&a=2&b=3'
54
- */
55
- export function stringify(data, options) {
56
- options = options || {};
57
-
58
- const result = [];
59
- function addToResult(key, value) {
60
- if (value == null) { value = ''; }
61
- // 忽略空值的情况
62
- if (value === '' && options.ignoreEmpty) { return; }
63
-
64
- result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
65
- }
66
-
67
- let key, value;
68
-
69
- // 避免在循环中生成匿名函数,提到循环外
70
- function loopItem(item) { addToResult(key, item); }
71
-
72
- for (key in data) {
73
- if (hasOwnProp(data, key)) {
74
- value = data[key];
75
- if (Array.isArray(value)) {
76
- value.forEach(loopItem);
77
- } else {
78
- addToResult(key, value);
79
- }
80
- }
81
- }
82
-
83
- return result.join('&');
84
- }
85
-
86
- /**
87
- * 把键值对集合序列化为查询字符串后拼接到指定URL。
88
- * @author luoliquan
89
- * @param {string} url 指定URL。
90
- * @param {Object|string} data 键值对集合。
91
- * @param {Object} [options] 参数。
92
- * @param {Boolean} [options.ignoreEmpty] 序列化时是否忽略空值(包括null、undefined、空字符串)。
93
- * @return {String} 处理后的URL。
94
- * @example
95
- * append('http://abc.com?a=1', { b: 2, c: 3 }); // 'http://abc.com?a=1&b=2&c=3'
96
- * append('http://abc.com', { a: 1, b: 2 }); // 'http://abc.com?a=1&b=2'
97
- */
98
- export function append(url, data, options) {
99
- if (url == null) { return url; }
100
- url = String(url);
101
-
102
- // 如果url中包含hash,要先剪出来
103
- const temp = url.indexOf('#');
104
- let hash = '';
105
- if (temp !== -1) {
106
- hash = url.substring(temp, url.length);
107
- url = url.substring(0, temp);
108
- }
109
-
110
- // 移除位于末尾的?和&,方便拼接
111
- url = url.replace(/[?&]$/, '');
112
-
113
- if (typeof data !== 'string') {
114
- data = stringify(data, options);
115
- } else {
116
- // 移除位于开头的?和&,方便拼接
117
- data = data.replace(/^[?&]/, '');
118
- }
119
-
120
- return url + (url.indexOf('?') !== -1 ? '&' : '?') + data + hash;
121
- }
package/src/storage.js DELETED
@@ -1,106 +0,0 @@
1
- /**
2
- * 本模块提供本地存储相关方法的封装。
3
- * @module storage
4
- */
5
-
6
- import { tryParseJSON } from './lang';
7
-
8
- /**
9
- * 本地存储调用封装。
10
- * @author luoliquan
11
- * @param {Object} storageType 存储类型。
12
- */
13
- export class StorageWrap {
14
- constructor(storageType) {
15
- this._storageType = storageType || {
16
- getItem() { return null; },
17
- setItem() {},
18
- removeItem() {}
19
- };
20
- }
21
-
22
- /**
23
- * 获取指定存储项的值。
24
- * @param {string} key 存储项键名。
25
- * @return {string} 存储项的值。
26
- */
27
- get(key) {
28
- return this._storageType.getItem(key);
29
- }
30
-
31
- /**
32
- * 获取指定存储项的值并解析为 JSON。
33
- * @param {string} key 存储项键名。
34
- * @return {Any} 解析结果。
35
- */
36
- getAsJSON(key) {
37
- return tryParseJSON(this.get(key));
38
- }
39
-
40
- /**
41
- * 写入指定存储项的值。
42
- * @param {string} key 存储项键名。
43
- * @param {Any} value 存储项的值。
44
- * @return {boolean} 写入是否成功。
45
- */
46
- set(key, value) {
47
- // 在浏览器的隐私模式下 setItem 会抛出异常
48
- // 但 getItem 和 removeItem 都不会
49
- try {
50
- this._storageType.setItem(key, value);
51
- return true;
52
- } catch (e) {
53
- return false;
54
- }
55
- }
56
-
57
- /**
58
- * 把指定值序列化为 JSON 字符串后写入到指定存储项。
59
- * @param {string} key 存储项键名。
60
- * @param {Any} value 存储项的值。
61
- * @return {boolean} 写入是否成功。
62
- */
63
- setAsJSON(key, value) {
64
- return this.set(key, JSON.stringify(value));
65
- }
66
-
67
- /**
68
- * 移除存储项。
69
- * @param {string} key 存储项键名。
70
- */
71
- remove(key) {
72
- this._storageType.removeItem(key);
73
- }
74
- }
75
-
76
-
77
- let sessionStorage, localStorage;
78
- if (typeof window !== 'undefined') {
79
- // Chrome 隐私模式,跨域 iframe 内访问本地存储的相关对象会抛出异常
80
- try {
81
- sessionStorage = window.sessionStorage;
82
- localStorage = window.localStorage;
83
- } catch (e) {
84
- }
85
- }
86
-
87
- /**
88
- * sessionStorage 存取方法(通过 StorageWrap 包装了 sessionStorage)。
89
- * @example
90
- * const user = { name: 'Tom', pet: 'cat' };
91
- * session.setAsJSON('user', user);
92
- * typeof session.get('user'); // 'string'
93
- * typeof session.getAsJSON('user'); // 'object'
94
- */
95
- export const session = new StorageWrap(sessionStorage);
96
-
97
- /**
98
- * localStorage 存取方法(通过 StorageWrap 包装了 localStorage)。
99
- * @example
100
- * const user = { name: 'Tom', pet: 'cat' };
101
- * local.setAsJSON('user', user);
102
- * local.getAsJSON('user');
103
- * typeof local.get('user'); // 'string'
104
- * typeof local.getAsJSON('user'); // 'object'
105
- */
106
- export const local = new StorageWrap(localStorage);
package/src/string.js DELETED
@@ -1,105 +0,0 @@
1
- /**
2
- * 本模块提供字符串处理相关方法。
3
- * @module string
4
- */
5
-
6
- import { extend } from './lang';
7
-
8
- /**
9
- * 获取字符串长度(非英文字符按2算)。
10
- * @author luoliquan
11
- * @param {string} str 字符串。
12
- * @param {number} [mode=2] 非英文字符按多少个字符算。
13
- * @return {number} 字符串长度。
14
- * @example
15
- * strLen('abcde;'); // 6
16
- * strLen('abc测试;'); // 9
17
- * strLen('abc测试;', 1); // 6
18
- */
19
- export function strLen(str, mode) {
20
- mode = Number(mode) || 2;
21
- let result = 0;
22
- for (let i = str.length - 1; i >= 0; i--) {
23
- result += str.charCodeAt(i) > 255 ? mode : 1;
24
- }
25
- return result;
26
- }
27
-
28
- /**
29
- * 如果目标字符串超出限制长度,则进行截断并拼接省略符号;否则返回目标字符串。
30
- * @author luoliquan
31
- * @param {string} str 目标字符串。
32
- * @param {number} length 限制的长度。
33
- * @param {Object} [options] 其他设置。
34
- * @param {number} [options.mode=2] 非英文字符按多少个字符算。
35
- * @param {string} [options.ellipsis='...'] 省略符号。
36
- * @return {string} 截断后的字符串。
37
- * @example
38
- * cutStr('测试一下', 5); // '测试...'
39
- * cutStr('测试一下', 8); // '测试一下'
40
- */
41
- export function cutStr(str, length, options) {
42
- options = extend({
43
- ellipsis: '...'
44
- }, options);
45
- options.mode = Math.max(Number(options.mode) || 2, 1);
46
-
47
- str = String(str);
48
- const len = strLen(str, options.mode);
49
-
50
- // 未超出长度,直接返回传入的字符串
51
- if (len <= length) { return str; }
52
-
53
- // 减去省略符长度
54
- length -= strLen(options.ellipsis, options.mode);
55
-
56
- let result = '', i = -1;
57
- while (length > 0 && ++i < len) {
58
- length -= str.charCodeAt(i) > 255 ? options.mode : 1;
59
- if (length >= 0) { result += str.charAt(i); }
60
- }
61
-
62
- result += options.ellipsis;
63
-
64
- return result;
65
- }
66
-
67
- /**
68
- * 把指定字符串中的 HTML 预留字符替换成 HTML 实体。
69
- * @author luoliquan
70
- * @param {string} str 指定字符串。
71
- * @return {string} 替换后的字符串。
72
- */
73
- export function escapeHTML(str) {
74
- if (str == null) { return str; }
75
- const map = {
76
- '"': '&quot;',
77
- '\'': '&#39;',
78
- '&': '&amp;',
79
- '<': '&lt;',
80
- '>': '&gt;'
81
- };
82
- return String(str).replace(/["'&<>]/g, (match) => {
83
- return map[match];
84
- });
85
- }
86
-
87
- /**
88
- * 移除指定字符串中的 HTML 标签。
89
- * @param {string} str 指定字符串。
90
- * @return {string} 处理后的字符串。
91
- */
92
- export function removeTags(str) {
93
- if (str == null) { return str; }
94
- return String(str).replace(/<.+?>/g, '');
95
- }
96
-
97
- /**
98
- * 把指定字符串中的换行符替换成 &lt;br /&gt;。
99
- * @param {string} str 指定字符串。
100
- * @return {string} 替换后的字符串。
101
- */
102
- export function nl2br(str) {
103
- if (str == null) { return str; }
104
- return String(str).replace(/\r?\n/g, '<br />');
105
- }
package/src/validate.js DELETED
@@ -1,42 +0,0 @@
1
- /**
2
- * 本模块提供字符串格式验证方法。
3
- * @module validate
4
- */
5
-
6
- /**
7
- * 检查目标字符串是否手机号码。
8
- * @author liumin
9
- * @param {string} str 目标字符串。
10
- * @return {boolean} 目标字符串是否手机号码。
11
- * @example
12
- * isPhoneNO('13800138000'); // true
13
- * isPhoneNO('a13800138000c'); // false
14
- */
15
- export function isPhoneNO(str) {
16
- return /^1[3-9]\d{9}$/.test(str);
17
- }
18
-
19
- /**
20
- * 检查目标字符串是否电子邮箱地址。
21
- * @author luoliquan
22
- * @param {string} str 目标字符串。
23
- * @return {boolean} 目标字符串是否电子邮箱地址。
24
- * @example
25
- * isEmail('me@polyv.net'); // true
26
- * isEmail('me@polyv_.net-'); // false
27
- */
28
- export function isEmail(str) {
29
- let temp = /^[\w-]+(?:\.[\w-]+)*@[\w-]+(?:\.[\w-]+)*\.[a-zA-Z]{2,}$/.test(str);
30
- if (temp) {
31
- temp = str.replace('@', '.').split('.');
32
- for (let i = temp.length - 1; i >= 0; i--) {
33
- // 每一段的开头和结尾都不能是连字符或下划线
34
- if (/^[-_]/.test(temp[i]) || /[_-]$/.test(temp[i])) {
35
- return false;
36
- }
37
- }
38
- return true;
39
- } else {
40
- return false;
41
- }
42
- }