Utils

Description:
  • 一些辅助工具方法
Source:
一些辅助工具方法

Methods

(static) dateTimeFormat(dateTime, format)

Description:
  • 日期格式化
Source:
Example
dateTimeFormat(new Date(1704067200000), "YYYY年MM月DD日"); // 2024年01月01日
dateTimeFormat(new Date(1704067200000), "HH时mm分ss秒sss"); // 08时00分00秒000
dateTimeFormat(new Date(1704067200000), "YYYY年MM月DD日 HH时mm分ss秒sss"); // 2024年01月01日 08时00分00秒000
Parameters:
Name Type Description
dateTime Date Date对象
format string 格式化字符串,遵循ISO8601标准(YYYYY-MM-DDTHH:mm:ss.sssZ)

(static) generateRandomId(length) → {string}

Description:
  • 生成一个(伪)随机ID
Source:
Example
const id = generateRandomId(); // 生成一个32个字符的ID
const id = generateRandomId(16); // 生成一个16个字符的ID
Parameters:
Name Type Default Description
length number 32 ID长度
Returns:
生成的ID
Type
string

(static) isEmpty(value) → {boolean}

Description:
  • 判断一个值是否为空
    这些情况会被判定为空:空字符串、null、undefined、NaN、空数组、空对象、空Map、空Set
Source:
Example
isEmpty(""); // true
isEmpty([]); // true
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(NaN); // true
isEmpty({}); // true
isEmpty(new Map()); // true
isEmpty(new Set()); // true

isEmpty(0); // false
isEmpty({a: 1}); // false
isEmpty(new Map().set("a", "1")); // false
Parameters:
Name Type Description
value any 任意值
Returns:
- 值是否为空
Type
boolean

(async, static) retry(callable, retryTimes, retryDelay, …args)

Description:
  • 函数失败重试
Source:
Example
async function updateFormData(formData) {
  const resp = await doUpdate(formData);
  if (resp.error) {
    throw Error(resp.error);
  }
}

export async function onClick() {
  // 当updateFormData失败时,等待500毫秒再次调用updateFormData,最多重试5次
  retrey(() => updateFormData(), 5, 500, { field_123: "value" })
}
Parameters:
Name Type Attributes Default Description
callable function 要执行的函数。如果函数抛出异常则进行重试, 支持函数返回Promise,如果返回的Promise被reject则进行重试
retryTimes number 3 重试次数
retryDelay number 300 重试延时,单位毫秒,默认300ms
args * <repeatable>
传递给callable的参数

(static) round(number, digits) → {number}

Description:
  • 四舍五入
Source:
Example
0.1 + 0.2; // 0.30000000000000004
round(0.1 + 0.2); // 0.3

0.123 * 3.4; // 0.41819999999999996
round(0.123 * 3.4); // 0.42
round(0.123 * 3.4, 3); // 0.418
Parameters:
Name Type Default Description
number number 数字
digits number 2 要保留的小数位数
Returns:
四舍五入后的数字
Type
number

(static) sleep(time) → {Promise}

Description:
  • sleep函数,可在异步场景中实现延时或者暂停执行
Source:
Example
async function batchUpdate(datas) {
  // 批量调用接口更新数据,每次更新之间等待1秒钟以防止频繁请求导致接口被限制
  for (const data of datas) {
    await doUpdate(data);
    await sleep(1000);
  }
}
Parameters:
Name Type Description
time number sleep时间,单位毫秒
Returns:
一个Promise,在time毫秒后被resolve
Type
Promise