sculp-js 0.0.2 → 0.1.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.
@@ -0,0 +1,67 @@
1
+ /*!
2
+ * sculp-js v0.1.0
3
+ * (c) 2023-2023 chandq
4
+ * Released under the MIT License.
5
+ */
6
+
7
+ import { STRING_ARABIC_NUMERALS, STRING_UPPERCASE_ALPHA, STRING_LOWERCASE_ALPHA } from './string.js';
8
+ import { isString, isNumber } from './type.js';
9
+
10
+ /**
11
+ * 随机整数
12
+ * @param {number} min
13
+ * @param {number} max
14
+ * @returns {number}
15
+ */
16
+ const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
17
+ const STRING_POOL = `${STRING_ARABIC_NUMERALS}${STRING_UPPERCASE_ALPHA}${STRING_LOWERCASE_ALPHA}`;
18
+ /**
19
+ * 随机字符串
20
+ * @param {number | string} length
21
+ * @param {string} pool
22
+ * @returns {string}
23
+ */
24
+ const randomString = (length, pool) => {
25
+ let _length = 0;
26
+ let _pool = STRING_POOL;
27
+ if (isString(pool)) {
28
+ _length = length;
29
+ _pool = pool;
30
+ }
31
+ else if (isNumber(length)) {
32
+ _length = length;
33
+ }
34
+ else if (isString(length)) {
35
+ _pool = length;
36
+ }
37
+ let times = Math.max(_length, 1);
38
+ let result = '';
39
+ const min = 0;
40
+ const max = _pool.length - 1;
41
+ if (max < 2)
42
+ throw new Error('字符串池长度不能少于 2');
43
+ while (times--) {
44
+ const index = randomNumber(min, max);
45
+ result += _pool[index];
46
+ }
47
+ return result;
48
+ };
49
+ /**
50
+ * 优先浏览器原生能力获取 UUID v4
51
+ * @returns {string}
52
+ */
53
+ function randomUuid() {
54
+ if (typeof URL === 'undefined' || !URL.createObjectURL || typeof Blob === 'undefined') {
55
+ const hex = '0123456789abcdef';
56
+ const model = 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx';
57
+ let str = '';
58
+ for (let i = 0; i < model.length; i++) {
59
+ const rnd = randomNumber(0, 15);
60
+ str += model[i] == '-' || model[i] == '4' ? model[i] : hex[rnd];
61
+ }
62
+ return str;
63
+ }
64
+ return /[^/]+$/.exec(URL.createObjectURL(new Blob()).slice())[0];
65
+ }
66
+
67
+ export { STRING_POOL, randomNumber, randomString, randomUuid };
package/lib/es/string.js CHANGED
@@ -1,9 +1,11 @@
1
1
  /*!
2
- * sculp-js v0.0.1
2
+ * sculp-js v0.1.0
3
3
  * (c) 2023-2023 chandq
4
4
  * Released under the MIT License.
5
5
  */
6
6
 
7
+ import { isString } from './type.js';
8
+
7
9
  /**
8
10
  * 将字符串转换为驼峰格式
9
11
  * @param {string} string
@@ -120,5 +122,35 @@ const stringEscapeHtml = (html) => {
120
122
  * @returns {string}
121
123
  */
122
124
  const stringFill = (length, value = ' ') => new Array(length).fill(value).join('');
125
+ /**
126
+ * 字符串的像素宽度
127
+ * @param {string} str 目标字符串
128
+ * @param {number} fontSize 字符串字体大小
129
+ * @param {boolean} isRemoveDom 计算后是否移除中间dom元素
130
+ * @return {*}
131
+ */
132
+ function getStrWidthPx(str, fontSize = 14, isRemoveDom = false) {
133
+ let strWidth = 0;
134
+ console.assert(isString(str), `${str} 不是有效的字符串`);
135
+ if (isString(str) && str.length > 0) {
136
+ let getEle = document.querySelector('#getStrWidth1494304949567');
137
+ if (!getEle) {
138
+ const _ele = document.createElement('span');
139
+ _ele.id = 'getStrWidth1494304949567';
140
+ _ele.style.fontSize = fontSize + 'px';
141
+ _ele.style.whiteSpace = 'nowrap';
142
+ _ele.style.visibility = 'hidden';
143
+ _ele.textContent = str;
144
+ document.body.appendChild(_ele);
145
+ getEle = _ele;
146
+ }
147
+ getEle.textContent = str;
148
+ strWidth = getEle.offsetWidth;
149
+ if (isRemoveDom) {
150
+ document.body.appendChild(getEle);
151
+ }
152
+ }
153
+ return strWidth;
154
+ }
123
155
 
124
- export { STRING_ARABIC_NUMERALS, STRING_LOWERCASE_ALPHA, STRING_UPPERCASE_ALPHA, stringAssign, stringCamelCase, stringEscapeHtml, stringFill, stringFormat, stringKebabCase };
156
+ export { STRING_ARABIC_NUMERALS, STRING_LOWERCASE_ALPHA, STRING_UPPERCASE_ALPHA, getStrWidthPx, stringAssign, stringCamelCase, stringEscapeHtml, stringFill, stringFormat, stringKebabCase };
package/lib/es/type.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * sculp-js v0.0.1
2
+ * sculp-js v0.1.0
3
3
  * (c) 2023-2023 chandq
4
4
  * Released under the MIT License.
5
5
  */
@@ -25,4 +25,4 @@ const isDate = (any) => typeIs(any) === 'Date';
25
25
  const isError = (any) => typeIs(any) === 'Error';
26
26
  const isRegExp = (any) => typeIs(any) === 'RegExp';
27
27
 
28
- export { typeIs as default, isArray, isBigInt, isBoolean, isDate, isError, isFunction, isNaN, isNull, isNumber, isObject, isPrimitive, isRegExp, isString, isSymbol, isUndefined };
28
+ export { typeIs as default, isArray, isBigInt, isBoolean, isDate, isError, isFunction, isNaN, isNull, isNumber, isObject, isPrimitive, isRegExp, isString, isSymbol, isUndefined, typeIs };
@@ -0,0 +1,79 @@
1
+ /*!
2
+ * sculp-js v0.1.0
3
+ * (c) 2023-2023 chandq
4
+ * Released under the MIT License.
5
+ */
6
+
7
+ import { numberToHex, HEX_POOL } from './number.js';
8
+ import { randomNumber } from './random.js';
9
+ import { isString, isNumber } from './type.js';
10
+
11
+ const padStartWithZero = (str, maxLength = 2) => String(str).padStart(maxLength, '0');
12
+ let safeNo = 0;
13
+ let lastTimestamp = 0;
14
+ // 安全后缀长度,按 1 毫秒运算 99999 次 JS 代码来进行估算
15
+ // 那么,补足长度为 5
16
+ // 时间戳模式长度为 13
17
+ // 取最长 5 + 13 = 18
18
+ const UNIQUE_NUMBER_SAFE_LENGTH = 18;
19
+ const FIX_SAFE_LENGTH = 5;
20
+ const TIMESTAMP_LENGTH = 13;
21
+ /**
22
+ * 生成唯一不重复数值
23
+ * @param {number} length
24
+ * @returns {string}
25
+ */
26
+ const uniqueNumber = (length = UNIQUE_NUMBER_SAFE_LENGTH) => {
27
+ const now = Date.now();
28
+ length = Math.max(length, UNIQUE_NUMBER_SAFE_LENGTH);
29
+ if (now !== lastTimestamp) {
30
+ lastTimestamp = now;
31
+ safeNo = 0;
32
+ }
33
+ const timestamp = `${now}`;
34
+ let random = '';
35
+ const rndLength = length - FIX_SAFE_LENGTH - TIMESTAMP_LENGTH;
36
+ if (rndLength > 0) {
37
+ const rndMin = 10 ** (rndLength - 1);
38
+ const rndMax = 10 ** rndLength - 1;
39
+ const rnd = randomNumber(rndMin, rndMax);
40
+ random = `${rnd}`;
41
+ }
42
+ const safe = padStartWithZero(safeNo, FIX_SAFE_LENGTH);
43
+ safeNo++;
44
+ return `${timestamp}${random}${safe}`;
45
+ };
46
+ const randomFromPool = (pool) => {
47
+ const poolIndex = randomNumber(0, pool.length - 1);
48
+ return pool[poolIndex];
49
+ };
50
+ /**
51
+ * 生成唯一不重复字符串
52
+ * @param {number | string} length
53
+ * @param {string} pool
54
+ * @returns {string}
55
+ */
56
+ const uniqueString = (length, pool) => {
57
+ let _length = 0;
58
+ let _pool = HEX_POOL;
59
+ if (isString(pool)) {
60
+ _length = length;
61
+ _pool = pool;
62
+ }
63
+ else if (isNumber(length)) {
64
+ _length = length;
65
+ }
66
+ else if (isString(length)) {
67
+ _pool = length;
68
+ }
69
+ let uniqueString = numberToHex(uniqueNumber(), _pool);
70
+ let insertLength = _length - uniqueString.length;
71
+ if (insertLength <= 0)
72
+ return uniqueString;
73
+ while (insertLength--) {
74
+ uniqueString += randomFromPool(_pool);
75
+ }
76
+ return uniqueString;
77
+ };
78
+
79
+ export { UNIQUE_NUMBER_SAFE_LENGTH, uniqueNumber, uniqueString };
package/lib/es/url.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * sculp-js v0.0.1
2
+ * sculp-js v0.1.0
3
3
  * (c) 2023-2023 chandq
4
4
  * Released under the MIT License.
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * sculp-js v0.0.1
2
+ * sculp-js v0.1.0
3
3
  * (c) 2023-2023 chandq
4
4
  * Released under the MIT License.
5
5
  */
package/lib/index.d.ts CHANGED
@@ -5,6 +5,7 @@ type AnyObject = Record<string | number, any>;
5
5
  type PartialDeep<T> = {
6
6
  [P in keyof T]?: PartialDeep<T[P]>;
7
7
  };
8
+ declare const typeIs: (any: unknown) => string;
8
9
  declare const isString: (any: unknown) => any is string;
9
10
  declare const isBoolean: (any: unknown) => any is boolean;
10
11
  declare const isSymbol: (any: unknown) => any is symbol;
@@ -33,7 +34,7 @@ declare const arrayLike: (any: unknown) => boolean;
33
34
  * @param {(val: V, idx: number) => any} iterator
34
35
  * @param reverse {boolean} 是否倒序
35
36
  */
36
- declare const arrayEach: <V>(array: ArrayLike<V>, iterator: (val: V, idx: number) => any, reverse?: boolean) => void;
37
+ declare const arrayEach: <V>(array: ArrayLike<V>, iterator: (val: V, idx: number, arr: ArrayLike<V>) => any, reverse?: boolean) => void;
37
38
  /**
38
39
  * 异步遍历数组,返回 false 中断遍历
39
40
  * @param {ArrayLike<V>} array
@@ -76,30 +77,6 @@ interface ITreeConf {
76
77
  * @return {[IdLike[], ITreeItem<V>[]]}
77
78
  */
78
79
  declare function getTreeIds<V>(tree: ArrayLike<V>, nodeId: IdLike, config?: ITreeConf): [IdLike[], ArrayLike<V>[]];
79
- /**
80
- * 异步ForEach函数
81
- * @param {array} array
82
- * @param {asyncFuntion} callback
83
- * // asyncForEach 使用范例如下
84
- // const start = async () => {
85
- // await asyncForEach(result, async (item) => {
86
- // await request(item);
87
- // count++;
88
- // });
89
-
90
- // console.log('发送次数', count);
91
- // }
92
-
93
- // for await...of 使用范例如下
94
- // const loadImages = async (images) => {
95
- // for await (const item of images) {
96
- // await request(item);
97
- // count++;
98
- // }
99
- // }
100
- * @return {*}
101
- */
102
- declare function asyncForEach(array: any[], callback: Function): Promise<void>;
103
80
 
104
81
  /**
105
82
  * 复制文本
@@ -214,6 +191,14 @@ declare function smoothScroll(options?: Partial<SmoothScrollOptions>): Promise<v
214
191
  type ReadyCallback = () => void;
215
192
  declare function isDomReady(): boolean;
216
193
  declare function onDomReady(callback: ReadyCallback): void;
194
+ /**
195
+ * 获取元素样式属性的计算值
196
+ * @param {HTMLElement} el
197
+ * @param {string} property
198
+ * @param {boolean} reNumber
199
+ * @return {string|number}
200
+ */
201
+ declare function getComputedCssVal(el: HTMLElement, property: string, reNumber?: boolean): string | number;
217
202
 
218
203
  interface Params<T = string | number> {
219
204
  [key: string]: T | Array<T>;
@@ -414,6 +399,14 @@ declare const stringEscapeHtml: (html: string) => string;
414
399
  * @returns {string}
415
400
  */
416
401
  declare const stringFill: (length: number, value?: string) => string;
402
+ /**
403
+ * 字符串的像素宽度
404
+ * @param {string} str 目标字符串
405
+ * @param {number} fontSize 字符串字体大小
406
+ * @param {boolean} isRemoveDom 计算后是否移除中间dom元素
407
+ * @return {*}
408
+ */
409
+ declare function getStrWidthPx(str: string, fontSize?: number, isRemoveDom?: boolean): number;
417
410
 
418
411
  interface Url {
419
412
  protocol: string;
@@ -502,4 +495,126 @@ interface ICanvasWM {
502
495
  */
503
496
  declare const genCanvasWM: (canvasWM: ICanvasWM) => void;
504
497
 
505
- export { type AnyArray, type AnyFunc, type AnyObject, type ArrayElements, type LooseParamValue, type LooseParams, type Params, type PartialDeep, type Replacer, STRING_ARABIC_NUMERALS, STRING_LOWERCASE_ALPHA, STRING_UPPERCASE_ALPHA, addClass, arrayEach, arrayEachAsync, arrayInsertBefore, arrayLike, arrayRemove, asyncForEach, asyncMap, calculateDate, calculateDateTime, chooseLocalFile, cloneDeep, cookieDel, cookieGet, cookieSet, copyText, deepTraversal, downloadBlob, downloadData, downloadHref, downloadURL, formatDate, genCanvasWM, getStyle, getTreeIds, hasClass, isArray, isBigInt, isBoolean, isDate, isDomReady, isError, isFunction, isNaN, isNull, isNumber, isObject, isPlainObject, isPrimitive, isRegExp, isString, isSymbol, isUndefined, objectAssign, objectEach, objectEachAsync, objectFill, objectGet, objectHas, objectMap, objectAssign as objectMerge, objectOmit, objectPick, onDomReady, pathJoin, pathNormalize, qsParse, qsStringify, removeClass, setStyle, smoothScroll, stringAssign, stringCamelCase, stringEscapeHtml, stringFill, stringFormat, stringKebabCase, urlDelParams, urlParse, urlSetParams, urlStringify, wait };
498
+ interface DebounceFunc<F extends AnyFunc> {
499
+ (...args: Parameters<F>): void;
500
+ cancel: () => void;
501
+ }
502
+ /**
503
+ * 防抖函数
504
+ * 当函数被连续调用时,该函数并不执行,只有当其全部停止调用超过一定时间后才执行1次。
505
+ * 例如:上电梯的时候,大家陆陆续续进来,电梯的门不会关上,只有当一段时间都没有人上来,电梯才会关门。
506
+ * @param {F} func
507
+ * @param {number} wait
508
+ * @returns {DebounceFunc<F>}
509
+ */
510
+ declare const debounce: <F extends AnyFunc>(func: F, wait?: number) => DebounceFunc<F>;
511
+ interface ThrottleFunc<F extends AnyFunc> {
512
+ (...args: Parameters<F>): void;
513
+ cancel: () => void;
514
+ }
515
+ /**
516
+ * 节流函数
517
+ * 节流就是节约流量,将连续触发的事件稀释成预设评率。 比如每间隔1秒执行一次函数,无论这期间触发多少次事件。
518
+ * 这有点像公交车,无论在站点等车的人多不多,公交车只会按时来一班,不会来一个人就来一辆公交车。
519
+ * @param {F} func
520
+ * @param {number} wait
521
+ * @param {boolean} immediate
522
+ * @returns {ThrottleFunc<F>}
523
+ */
524
+ declare const throttle: <F extends AnyFunc>(func: F, wait: number, immediate?: boolean) => ThrottleFunc<F>;
525
+ interface OnceFunc<F extends AnyFunc> {
526
+ (...args: Parameters<F>): ReturnType<F>;
527
+ }
528
+ /**
529
+ * 单次函数
530
+ * @param {AnyFunc} func
531
+ * @returns {AnyFunc}
532
+ */
533
+ declare const once: <F extends AnyFunc = AnyFunc>(func: F) => OnceFunc<F>;
534
+ /**
535
+ * 设置全局变量
536
+ * @param {string | number | symbol} key
537
+ * @param val
538
+ */
539
+ declare function setGlobal(key: string | number | symbol, val?: any): void;
540
+ /**
541
+ * 设置全局变量
542
+ * @param {string | number | symbol} key
543
+ * @param val
544
+ */
545
+ declare function getGlobal<T>(key: string | number | symbol): T | void;
546
+
547
+ /**
548
+ * 随机整数
549
+ * @param {number} min
550
+ * @param {number} max
551
+ * @returns {number}
552
+ */
553
+ declare const randomNumber: (min: number, max: number) => number;
554
+ declare const STRING_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
555
+ interface RandomString {
556
+ (length: number, pool: string): string;
557
+ (length: number): string;
558
+ (pool: string): string;
559
+ (): string;
560
+ }
561
+ /**
562
+ * 随机字符串
563
+ * @param {number | string} length
564
+ * @param {string} pool
565
+ * @returns {string}
566
+ */
567
+ declare const randomString: RandomString;
568
+ /**
569
+ * 优先浏览器原生能力获取 UUID v4
570
+ * @returns {string}
571
+ */
572
+ declare function randomUuid(): string;
573
+
574
+ declare const HEX_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
575
+ /**
576
+ * 将十进制转换成任意进制
577
+ * @param {number | string} decimal 十进制数值或字符串,可以是任意长度,会使用大数进行计算
578
+ * @param {string} [hexPool] 进制池,默认 62 进制
579
+ * @returns {string}
580
+ */
581
+ declare const numberToHex: (decimal: number | string, hexPool?: string) => string;
582
+ /**
583
+ * 缩写
584
+ * @param {number | string} num
585
+ * @param {Array<string>} units
586
+ * @param {number} ratio
587
+ * @param {number} exponent
588
+ * @returns {string}
589
+ */
590
+ declare const numberAbbr: (num: number | string, units: Array<string>, ratio?: number, exponent?: number) => string;
591
+ /**
592
+ * 将数字格式化成千位分隔符显示的字符串
593
+ * @param {number} val 数字
594
+ * @param {'int' | 'float'} type 展示分段显示的类型 int:整型 | float:浮点型
595
+ * @return {string}
596
+ */
597
+ declare function formatNumber(val: number, type?: string): string;
598
+
599
+ declare const UNIQUE_NUMBER_SAFE_LENGTH = 18;
600
+ /**
601
+ * 生成唯一不重复数值
602
+ * @param {number} length
603
+ * @returns {string}
604
+ */
605
+ declare const uniqueNumber: (length?: number) => string;
606
+ interface UniqueString {
607
+ (length: number, pool: string): string;
608
+ (length: number): string;
609
+ (pool: string): string;
610
+ (): string;
611
+ }
612
+ /**
613
+ * 生成唯一不重复字符串
614
+ * @param {number | string} length
615
+ * @param {string} pool
616
+ * @returns {string}
617
+ */
618
+ declare const uniqueString: UniqueString;
619
+
620
+ export { type AnyArray, type AnyFunc, type AnyObject, type ArrayElements, HEX_POOL, type LooseParamValue, type LooseParams, type Params, type PartialDeep, type Replacer, STRING_ARABIC_NUMERALS, STRING_LOWERCASE_ALPHA, STRING_POOL, STRING_UPPERCASE_ALPHA, UNIQUE_NUMBER_SAFE_LENGTH, addClass, arrayEach, arrayEachAsync, arrayInsertBefore, arrayLike, arrayRemove, asyncMap, calculateDate, calculateDateTime, chooseLocalFile, cloneDeep, cookieDel, cookieGet, cookieSet, copyText, debounce, deepTraversal, downloadBlob, downloadData, downloadHref, downloadURL, formatDate, formatNumber, genCanvasWM, getComputedCssVal, getGlobal, getStrWidthPx, getStyle, getTreeIds, hasClass, isArray, isBigInt, isBoolean, isDate, isDomReady, isError, isFunction, isNaN, isNull, isNumber, isObject, isPlainObject, isPrimitive, isRegExp, isString, isSymbol, isUndefined, numberAbbr, numberToHex, objectAssign, objectEach, objectEachAsync, objectFill, objectGet, objectHas, objectMap, objectAssign as objectMerge, objectOmit, objectPick, onDomReady, once, pathJoin, pathNormalize, qsParse, qsStringify, randomNumber, randomString, randomUuid, removeClass, setGlobal, setStyle, smoothScroll, stringAssign, stringCamelCase, stringEscapeHtml, stringFill, stringFormat, stringKebabCase, throttle, typeIs, uniqueNumber, uniqueString, urlDelParams, urlParse, urlSetParams, urlStringify, wait };