Commit 0c1fb08a by liimin

refactor(recorder): 重构业务数据处理与缓存机制

- 将业务数据缓存逻辑从 RecordService 移至策略层,遵循单一职责原则
- 在 IRecorderStrategy 接口中新增缓存操作方法,使策略能够自主管理业务数据
- 修改 IBusinessDataHandler.handle 方法签名,增加 recordId 参数以支持策略级缓存决策
- 重构 DefaultRecorderStrategy 实现缓存写入、消费和清理逻辑
- 优化 RecordCache 使其支持通用缓存配置,便于策略扩展
- 统一使用严格相等运算符 (===) 替换松散相等运算符 (==)
- 修复注释拼写错误 (@Description 替换 @Descripttion)
- 更新 cspell 词典,添加缺失的技术词汇
1 parent a0bca4af
......@@ -2,7 +2,7 @@ import { startRecord, StartRecordOptions, StartRecordSuccess, stopRecord, StopRe
import { logger } from "../logger";
/*
* @Descripttion:
* @Description:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-04 18:17:23
......
import type { IDBRecord, RecordData } from "./types";
/*
* @Descripttion:
* @Description:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:34:39
......@@ -43,7 +43,7 @@ class DBRecord extends DBBase implements IDBRecord {
}
static getInstance(): DBRecord {
if (DBRecord.instance == null) {
if (DBRecord.instance === null) {
DBRecord.instance = new DBRecord();
}
return DBRecord.instance;
......@@ -71,6 +71,10 @@ class DBRecord extends DBBase implements IDBRecord {
return this.parseRecords(records);
}
getStrategy(): IRecorderStrategy {
return this.strategy;
}
/**
* 获取进行中/临时的接待记录 (recordStatus = 0)
*/
......@@ -112,7 +116,7 @@ class DBRecord extends DBBase implements IDBRecord {
// 更好的做法是:
// 1. setStrategy 改为 async (但这会破坏接口签名,如果有接口的话)
// 2. 在内部启动一个 async 任务,并捕获错误
if (this.db != null) {
if (this.db !== null) {
// 使用 IIFE 或 then/catch 处理异步
this.ensureColumns().catch(error => {
logger.error(`DBRecord: setStrategy ensureColumns failed: ${error}`, "DBRecord");
......@@ -130,8 +134,8 @@ class DBRecord extends DBBase implements IDBRecord {
const existingColumns = columnInfo.map((col: any): string => {
const c = col as UTSJSONObject;
const name = c.name;
return (name != null ? name : "") as string;
}).filter((name: string): boolean => name != "");
return (name !== null ? name : "") as string;
}).filter((name: string): boolean => name !== "");
logger.info(`DBRecord: existingColumns: ${JSON.stringify(existingColumns)}`, "DBRecord");
......@@ -144,7 +148,7 @@ class DBRecord extends DBBase implements IDBRecord {
const name = parts[0];
// 简单的判断,如果 name 不为空且不在 existingColumns 中
if (name != "" && !existingColumns.includes(name)) {
if (name !== "" && !existingColumns.includes(name)) {
// 重新组装 definition: 去掉 name,剩下的就是 definition
const definition = colDef.slice(name.length).trim();
columnsToAdd.push({ name, definition });
......@@ -200,7 +204,7 @@ class DBRecord extends DBBase implements IDBRecord {
// 使用 JSON 转换是一种通用的方式
const recordStr = JSON.stringify(itemObj);
const record = JSON.parse<RecordData>(recordStr);
if (record != null) {
if (record !== null) {
res.push(record);
}
} catch (error) {
......
......@@ -4,21 +4,11 @@
* @Author: limin
* @Date: 2026-01-14 14:30:10
* @LastEditors: limin
* @LastEditTime: 2026-03-06 14:22:59
* @LastEditTime: 2026-03-06 15:04:58
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordCache.uts
*/
import { logger } from "../logger/index.uts";
type CacheConfigItem = {
keyPrefix: string
targetField: string
}
const CACHE_CONFIG_MATERIAL_POINTS = {
keyPrefix: "MATERIAL_POINTS_", // Storage Key 前缀
targetField: "receptionCustomerMaterialPointList" // 对应的 Record 字段名
} as CacheConfigItem;
/**
* 记录缓存管理器
* 统一管理大字段的暂存、合并与清理
......@@ -27,16 +17,16 @@ export default class RecordCache {
/**
* 清理指定记录的所有缓存
* @param {string} recordId
* @param {string[]} keys - 需要清理的缓存 key 列表
*/
static clearAll(recordId: string) {
if (recordId == "") return;
static clearAll(recordId: string, keys: string[]) {
if (recordId === "") return;
const configs = [CACHE_CONFIG_MATERIAL_POINTS];
configs.forEach(config => {
keys.forEach(keyPrefix => {
try {
uni.removeStorage({
key: config.keyPrefix + recordId,
fail: (res) => {}
key: keyPrefix + recordId,
fail: () => {}
});
} catch {}
});
......@@ -44,26 +34,31 @@ export default class RecordCache {
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {object} record - 记录对象 (仅用于获取ID)
* @param {string} recordId - 记录 ID
* @param {Map<string, string>} cacheConfig - 缓存配置 Map<KeyPrefix, TargetField>
* @returns {object} 从缓存恢复的数据对象
*/
static async consumeAll(record: any): Promise<UTSJSONObject> {
const recordObj = record as UTSJSONObject;
const recordId = recordObj.getString("id");
if (recordId == null) return {};
static async consumeAll(recordId: string, cacheConfig: Map<string, string>): Promise<UTSJSONObject> {
if (recordId === "") return {};
const restoredData: UTSJSONObject = {};
// 遍历配置
// 目前只有一个,直接硬编码处理,或者用 Object.values (UTS可能不支持)
const configs = [CACHE_CONFIG_MATERIAL_POINTS];
for (const config of configs) {
const keyList: string[] = [];
// UTS Map iteration workaround: manually iterate using forEach on the map itself
cacheConfig.forEach((_, key) => {
keyList.push(key);
});
for (const keyPrefix of keyList) {
const targetField = cacheConfig.get(keyPrefix);
if (targetField === null) continue;
try {
const key = config.keyPrefix + recordId;
const storageKey = keyPrefix + recordId;
const data = await new Promise<any | null>((resolve) => {
uni.getStorage({
key,
key: storageKey,
success: (res) => {
resolve(res.data);
},
......@@ -73,17 +68,17 @@ export default class RecordCache {
});
});
if (data != null && data != "") {
restoredData[config.targetField] = data;
if (data !== null && data !== "") {
restoredData[targetField] = data;
uni.removeStorage({
key,
key: storageKey,
fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${key} failed: ${res.errMsg}`, "RecordCache");
logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache");
}
}); // 消费即焚
}
} catch (error) {
logger.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${error}`, "RecordCache");
logger.warn(`RecordCacheManager: Consume ${keyPrefix} failed: ${error}`, "RecordCache");
}
}
return restoredData;
......@@ -92,27 +87,21 @@ export default class RecordCache {
/**
* 暂存数据
* @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG)
* @param {string} keyPrefix - 缓存 Key 前缀
* @param {any} data - 数据
*/
static set(recordId: string, type: string, data: any) {
// UTS 中对象键访问需要 specific
let config: CacheConfigItem | null = null;
if (type == "MATERIAL_POINTS") {
config = CACHE_CONFIG_MATERIAL_POINTS;
}
if (recordId == "" || config == null) return;
static set(recordId: string, keyPrefix: string, data: any) {
if (recordId === "" || keyPrefix === "") return;
try {
uni.setStorage({
key: config.keyPrefix + recordId,
key: keyPrefix + recordId,
data,
fail: (res) => {
logger.error(`RecordCacheManager: Set ${type} failed: ${res.errMsg}`, "RecordCache");
logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${res.errMsg}`, "RecordCache");
}
});
} catch (error) {
logger.error(`RecordCacheManager: Set ${type} failed: ${error}`, "RecordCache");
logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${error}`, "RecordCache");
}
}
}
......@@ -111,7 +111,7 @@ export class RecordService {
async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> {
return new Promise((resolve) => {
checkPermission("Microphone", (result) => {
if (result == "granted") {
if (result === "granted") {
resolve(true);
} else {
requestPermissions({
......@@ -147,7 +147,7 @@ export class RecordService {
}
isReceptioning(): boolean {
return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.endReasonType == 1);
return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.endReasonType === 1);
}
onAudioError(error: any) {
......@@ -158,11 +158,11 @@ export class RecordService {
async onAudioStart(res: StartRecordSuccess) {
try {
// 安全检查:防止 Service 已重置导致空指针
if (this.audioManager == null) {
if (this.audioManager === null) {
logger.warn("〖RecordService〗 == onAudioStart called but audioManager is null", "RecordService");
return;
}
if (this.record == null) {
if (this.record === null) {
logger.warn("〖RecordService〗 == onAudioStart called but record is null", "RecordService");
return;
}
......@@ -203,7 +203,7 @@ export class RecordService {
}
async onAudioStop(res: any) {
if (this.audioManager?.isRecording == true) {
if (this.audioManager?.isRecording === true) {
logger.info("【录音服务RecordService】 == 接待中,再次开启录音! ", "RecordService");
this.audioManager?.start();
} else {
......@@ -217,8 +217,8 @@ export class RecordService {
this.stopAudioRecord();
}
reportError(msg: string, errorMsg: string) {
logger.error({ msg: `【录音服务RecordService】 == ${msg}` }, "RecordService");
reportError(msg: string, error: any) {
logger.error({ msg: `【录音服务RecordService】 == ${msg} error: ${error}` }, "RecordService");
}
reset() {
......@@ -293,7 +293,7 @@ export class RecordService {
logger.info("【录音服务RecordService】 == 结束接待! ", "RecordService");
this.stop();
try {
if (this.record != null) {
if (this.record !== null) {
await this.saveAndClearRecord(isNotSave);
} else {
logger.warn("【录音服务RecordService】 == 结束接待时 record 为空", "RecordService");
......@@ -331,18 +331,13 @@ export class RecordService {
updateBusinessData(type: string, data: any | null) {
if (!this.isReceptioning()) return;
// 委托给 Handler 处理
const result = this.businessHandler.handle(type, data);
// 处理结果:可能是 DB 更新,也可能是缓存操作
// 委托给 Handler 处理,传入 recordId 以便策略自行决定缓存还是持久化
const result = this.businessHandler.handle(type, data, this.record?.currentRecord?.id ?? "");
// 如果策略返回 null,说明已经由策略自行处理(如缓存)或无需处理
if (result === null) return;
if (result._isCache === true) {
const list = result.value as UTSJSONObject[];
if (this.record !== null) {
this.record.cacheMaterialPoints(list); // 这里其实也可以泛化,比如 cache(key, val)
}
} else {
this.record?.updatePreRecords(result);
}
// 如果策略返回了数据对象,则交由 Service 进行预记录持久化 (updatePreRecords)
this.record?.updatePreRecords(result);
}
}
......
import { storage } from "../../../utils/storage.uts";
import RecordCache from "../RecordCache.uts";
import { BusinessDataType } from "../types/handler.uts";
import { IRecorderStrategy } from "../types/strategy.uts";
......@@ -8,6 +9,50 @@ import { IRecorderStrategy } from "../types/strategy.uts";
*/
export class DefaultRecorderStrategy implements IRecorderStrategy {
// 缓存配置:Key前缀 -> 目标字段名
private cacheConfig: Map<string, string> = new Map([
["MATERIAL_POINTS_", "receptionCustomerMaterialPointList"]
]);
/**
* 实现缓存写入逻辑
*/
cacheBusinessData(recordId: string, type: string, data: any): void {
// 映射 type 到 keyPrefix
let keyPrefix = "";
if (type == "MATERIAL_POINTS") {
keyPrefix = "MATERIAL_POINTS_";
}
// 如果有更多类型,可以在这里扩展,或者直接传入 keyPrefix
if (keyPrefix != "") {
RecordCache.set(recordId, keyPrefix, data);
}
}
/**
* 实现缓存清理逻辑
*/
clearBusinessCache(recordId: string): void {
const keyList: string[] = [];
this.cacheConfig.forEach((_, key) => {
keyList.push(key);
});
RecordCache.clearAll(recordId, keyList);
}
/**
* 实现缓存消费逻辑
*/
async consumeBusinessCache(recordId: string, currentRecord: UTSJSONObject): Promise<UTSJSONObject> {
// 调用通用缓存管理器的消费方法,传入当前策略的配置
const restored = await RecordCache.consumeAll(recordId, this.cacheConfig);
// 合并到当前记录
const result = Object.assign({}, currentRecord, restored);
return result;
}
getBussinessType(sceneType: any | null): number {
return sceneType === 0 ? 1 : 2; // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
}
......@@ -32,7 +77,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
const sceneType = obj.get("sceneType");
const dynamicAttrs = {
bussinessType: this.getBussinessType(sceneType)
bussinessType: this.getBussinessType(sceneType)
};
return dynamicAttrs;
} catch (error) {
......@@ -83,7 +128,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
];
}
handle(type: string, data: any | null): null | UTSJSONObject {
handle(type: string, data: any | null, recordId: string): null | UTSJSONObject {
switch (type) {
case BusinessDataType.BOOK as string: {
return this.processBookList(data as UTSJSONObject[]);
......@@ -92,7 +137,19 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
return this.processCustomerInfo(data as null | UTSJSONObject);
}
case BusinessDataType.MATERIAL as string: {
return this.processMaterialPoints(data as UTSJSONObject[]);
// 直接在这里进行缓存写入
const result = this.processMaterialPoints(data as UTSJSONObject[]);
// 检查是否需要缓存
if (result.getBoolean("_isCache") === true) {
const key = result.getString("key");
const val = result.get("value");
if (key !== null && val !== null) {
this.cacheBusinessData(recordId, key, val);
}
// 返回 null,表示 Service 不需要再做任何处理(包括更新 DB)
return null;
}
return result;
}
case BusinessDataType.STATUS as string: {
return this.processReceptionStatus(data as string);
......
......@@ -23,9 +23,10 @@ export interface IBusinessDataHandler {
* 通用数据处理方法
* @param type 数据类型标识 (建议使用 BusinessDataType 枚举值)
* @param data 原始业务数据
* @param recordId 当前记录ID
* @returns 处理后的数据 (用于更新到数据库或缓存)
* 返回 null 表示无需处理或忽略
* 返回带有 _isCache: true 的对象表示缓存操作
*/
handle(type: string, data: any | null): null | UTSJSONObject
handle(type: string, data: any | null, recordId: string): null | UTSJSONObject
}
import { IBusinessDataHandler } from './handler'
import { IBusinessDataHandler } from "./handler";
/**
* 录音业务策略接口
......@@ -31,4 +31,26 @@ export interface IRecorderStrategy extends IBusinessDataHandler {
* 这些数据通常在初始化时可能还未就绪,或者会动态变化
*/
getDynamicAttributes(): UTSJSONObject
/**
* 业务缓存处理:将业务数据存入缓存
* @param recordId 记录ID
* @param type 缓存子类型 (由 Handler 返回的 key)
* @param data 数据载荷
*/
cacheBusinessData(recordId: string, type: string, data: any): void
/**
* 业务缓存消费:从缓存中恢复所有业务数据并合并到记录中
* @param recordId 记录ID
* @param currentRecord 当前的记录对象(用于合并)
* @returns 包含恢复后数据的完整对象
*/
consumeBusinessCache(recordId: string, currentRecord: UTSJSONObject): Promise<UTSJSONObject>
/**
* 清理该记录的所有业务缓存
* @param recordId 记录ID
*/
clearBusinessCache(recordId: string): void
}
......@@ -40,7 +40,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
};
const policyBase64 = this.getPolicyBase64(policyObj);
// 增加 null 检查
if (accessKeySecret == null) {
if (accessKeySecret === null) {
console.error("[AliUniUploadStrategy] accessKeySecret is null");
throw new Error("accessKeySecret is null");
}
......@@ -62,7 +62,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
name: "file",
formData: formData as UTSJSONObject,
success: (res) => {
if (res.statusCode == 200 || res.statusCode == 204) {
if (res.statusCode === 200 || res.statusCode === 204) {
logger.info(`[AliUniUploadStrategy] 上传成功: ${objectKey}`, "FileUploadService");
const url = `${host}/${objectKey}`;
......@@ -92,7 +92,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
*/
getPolicyBase64(policyObj: any): string {
const policyStr = JSON.stringify(policyObj);
if (policyStr == null) return "";
if (policyStr === null) return "";
return base64Encode(policyStr).replaceAll("\n", "");
}
......
/*
* @Descripttion: 通用文件上传服务 (策略模式)
* @Description: 通用文件上传服务 (策略模式)
* @version: 1.1.0
* @Author: limin
* @Date: 2026-03-01
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\uploader\FileUploadService.uts
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\uploader\FileUploadService.uts
*/
import { logger } from "../logger/index.uts";
......@@ -27,10 +27,10 @@ class FileUploadService {
}
static getInstance(): FileUploadService {
if (FileUploadService.instance == null) {
if (FileUploadService.instance === null) {
FileUploadService.instance = new FileUploadService();
}
return FileUploadService.instance!;
return FileUploadService.instance;
}
/**
......@@ -38,17 +38,25 @@ class FileUploadService {
* @param type 策略类型
*/
setStrategy(type: UploadStrategyType) {
if (type == UploadStrategyType.ALI_OSS) {
this.strategy = new AliOSSUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService");
} else if (type == UploadStrategyType.UNI_UPLOAD) {
this.strategy = new UniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService");
} else if (type == UploadStrategyType.ALI_UNI) {
this.strategy = new AliUniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService");
} else {
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService");
switch (type) {
case UploadStrategyType.ALI_OSS: {
this.strategy = new AliOSSUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService");
break;
}
case UploadStrategyType.ALI_UNI: {
this.strategy = new AliUniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService");
break;
}
case UploadStrategyType.UNI_UPLOAD: {
this.strategy = new UniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService");
break;
}
default: {
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService");
}
}
}
......
......@@ -7,12 +7,12 @@ import { IUploadStrategy } from "./IUploadStrategy.uts";
export class UniUploadStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString("filePath");
if (filePath == null || filePath == "") {
if (filePath === null || filePath === "") {
throw new Error("filePath is required");
}
const uploadUrl = options.getString("uploadUrl");
if (uploadUrl == null || uploadUrl == "") {
if (uploadUrl === null || uploadUrl === "") {
throw new Error("uploadUrl is required for UniUploadStrategy");
}
......
......@@ -13,7 +13,7 @@ export function isArray(value: any): boolean {
* @example isObject([]) // false
*/
export function isObject(value: any): boolean {
return typeof value == "object" && !Array.isArray(value) && !isNull(value);
return typeof value === "object" && !Array.isArray(value) && !isNull(value);
}
/**
......@@ -22,7 +22,7 @@ export function isObject(value: any): boolean {
* @example isString(123) // false
*/
export function isString(value: any): boolean {
return typeof value == "string";
return typeof value === "string";
}
/**
......@@ -31,7 +31,7 @@ export function isString(value: any): boolean {
* @example isNumber('123') // false
*/
export function isNumber(value: any): boolean {
return typeof value == "number" && !isNaN(value);
return typeof value === "number" && !isNaN(value);
}
/**
......@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean {
* @example isBoolean(1) // false
*/
export function isBoolean(value: any): boolean {
return typeof value == "boolean";
return typeof value === "boolean";
}
/**
......@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean {
* @example isFunction({}) // false
*/
export function isFunction(value: any): boolean {
return typeof value == "function";
return typeof value === "function";
}
/**
......@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean {
*/
export function isEmpty(value: any): boolean {
if (isArray(value)) {
return (value as any[]).length == 0;
return (value as any[]).length === 0;
}
if (isString(value)) {
......@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean {
}
if (isObject(value)) {
return keys(value).length == 0;
return keys(value).length === 0;
}
return false;
......@@ -93,19 +93,19 @@ export function isEmpty(value: any): boolean {
* 返回对象的所有键名
* @example keys({a: 1, b: 2}) // ['a', 'b']
*/
export const nullValues = [null, ""]
export const nullValues = [null, ""];
/**
* 格式化日期时间
*/
export function convertDateTimeFormat(date: Date, separator: string): string {
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
const hours = date.getHours().toString().padStart(2, '0')
const minutes = date.getMinutes().toString().padStart(2, '0')
const seconds = date.getSeconds().toString().padStart(2, '0')
return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`;
}
/**
......@@ -138,7 +138,7 @@ export function getUUID(): string {
* @example first([1, 2, 3]) // 1
* @example first([]) // null
*/
export function first<T>(array: T[]): T | null {
export function first<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[0] : null;
}
......@@ -147,7 +147,7 @@ export function first<T>(array: T[]): T | null {
* @example last([1, 2, 3]) // 3
* @example last([]) // null
*/
export function last<T>(array: T[]): T | null {
export function last<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[array.length - 1] : null;
}
......@@ -214,8 +214,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U):
if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) {
result.push(iteratee(array[i], i));
for (const [i, element] of array.entries()) {
result.push(iteratee(element, i));
}
return result;
......@@ -233,8 +233,8 @@ export function reduce<T, U>(
if (!isArray(array)) return initialValue;
let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) {
accumulator = iteratee(accumulator, array[i], i);
for (const [i, element] of array.entries()) {
accumulator = iteratee(accumulator, element, i);
}
return accumulator;
......@@ -247,8 +247,8 @@ export function reduce<T, U>(
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
return false;
}
}
......@@ -263,8 +263,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo
export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return true;
}
}
......@@ -282,8 +282,7 @@ export function uniq<T>(array: T[]): T[] {
const result: T[] = [];
const seen = new Map<T, boolean>();
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
const key = item;
if (!seen.has(item)) {
seen.set(key, true);
......@@ -303,8 +302,7 @@ export function flatten(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...(item as any[]));
} else {
......@@ -324,8 +322,7 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...flattenDeep(item as any[]));
} else {
......@@ -345,11 +342,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array];
return result.sort((a, b) => {
if (typeof a == "number" && typeof b == "number") {
if (typeof a === "number" && typeof b === "number") {
return order == "asc" ? a - b : b - a;
}
if (typeof a == "string" && typeof b == "string") {
if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
}
......@@ -389,15 +386,14 @@ export function groupBy<T>(array: T[], key: string) {
const result = {};
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
let value = get(item as any, key)!;
if (typeof value == "number") {
if (typeof value === "number") {
value = value.toString();
}
if (typeof value == "string") {
if (typeof value === "string") {
if (!isArray(result[value])) {
result[value] = new Array<T>();
}
......@@ -423,7 +419,7 @@ export function assign(...items: any[]) {
* @example nth([1, 2, 3], 1) // 2
* @example nth([1, 2, 3], -1) // 3
*/
export function nth<T>(array: T[], index: number): T | null {
export function nth<T>(array: T[], index: number): null | T {
if (index >= 0) {
return array[index];
}
......@@ -450,9 +446,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = [];
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
result.push(array[i]);
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
result.push(element);
}
}
......@@ -467,9 +463,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
if (isArray(data)) {
const array = data as T[];
for (let i = 0; i < array.length; i++) {
if (array[i] != null) {
iteratee(array[i], i);
for (const [i, element] of array.entries()) {
if (element != null) {
iteratee(element, i);
}
}
}
......@@ -479,12 +475,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
* 查找数组中第一个满足条件的元素
* @example find([1, 2, 3, 4], x => x > 2) // 3
*/
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): T | null {
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): null | T {
if (!isArray(array)) return null;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return array[i];
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return element;
}
}
return null;
......@@ -497,8 +493,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool
export function forInObject(data: any, iteratee: (value: any, key: string) => void): void {
if (isObject(data)) {
const objKeys = keys(data);
for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i];
for (const key of objKeys) {
iteratee(get(data, key)!, key);
}
}
......@@ -595,9 +590,9 @@ export function random(min: number, max: number): number {
*/
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5
let bytes = window.atob(data.split(",")[1]);
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
const bytes = window.atob(data.split(",")[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
......@@ -629,17 +624,33 @@ export function isEqual(a: any, b: any): boolean {
* @returns 替换后的字符串
*/
export function replaceAll(text: string, find: string, replace: string): string {
if (text.indexOf(find) == -1) {
return text
}
const parts = text.split(find)
let res = ""
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
res = res + part
if (i < parts.length - 1) {
res = res + replace
}
}
return res
if (text.indexOf(find) == -1) {
return text;
}
const parts = text.split(find);
let res = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
res = res + part;
if (i < parts.length - 1) {
res = res + replace;
}
}
return res;
}
/**
* 深拷贝对象
* @param obj 要拷贝的对象
* @returns 拷贝后的对象
*/
export function deepClone<T>(obj: any): null | T {
// UTS 要求返回类型明确包含 null
if (obj == null) {
return null;
}
if (typeof obj === "object") {
return JSON.parse<T>(JSON.stringify(obj));
}
return obj as T;
}
......@@ -4,7 +4,6 @@
"language": "en,en-US",
"allowCompoundWords": true,
"words": [
"wxml",
"acmr",
"antd",
"antdv",
......@@ -18,10 +17,13 @@
"esno",
"etag",
"execa",
"hmac",
"iconify",
"iconoir",
"intlify",
"limin",
"lockb",
"lsaccess",
"lucide",
"minh",
"minw",
......@@ -46,6 +48,7 @@
"uicons",
"unplugin",
"unref",
"UTSJSONObject",
"venus",
"venusjs",
"vite",
......@@ -53,6 +56,7 @@
"vitepress",
"vnode",
"vueuse",
"wxml",
"yxxx"
],
"ignorePaths": [
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!