TypeScript 中的 "=>" 真的很好用!!!

class funs
{ public $scope: IBarPadScope; constructor($scope: IBarPadScope) { this.$scope = $scope; }
    public createLoadPhoneOrders(startTime?: string): () => void {
        return () => {
            startTime = startTime || moment().format("YYYY-MM-DD 00:00:00");
            this.$scope.socket.emit('command',
                {
                    command: 'query',
                    data: {
                        Node: this.$scope.sys.node,
                        CreatedTime: { '$gte': startTime }
                    },
                    document:'PhoneOrders'
                },
                (err, r: PhoneOrder[]) => {
                    this.$scope.$apply(() =>
                    {
                        this.$scope.allPhoneOrders = r;
                    });
            });
        };
    }
}

可以看到多级子函数调用 this一直指向的是funs的实例

看看编译出来的js的代码

funs.prototype.createLoadPhoneOrders = function (startTime) {
        var _this = this;
        return function () {
            startTime = startTime || moment().format("YYYY-MM-DD 00:00:00");
            _this.$scope.socket.emit('command', {
                command: 'query',
                data: {
                    Node: _this.$scope.sys.node,
                    CreatedTime: { '$gte': startTime }
                },
                document: 'PhoneOrders'
            }, function (err, r) {
                _this.$scope.$apply(function () {
                    _this.$scope.allPhoneOrders = r;
                });
            });
        };
    };

 

转载于:https://www.cnblogs.com/skytouchzyt/p/5232735.html

importYdwp = ( data: { Year: string Month: string Tbpc: string /** @format binary */ File: File }, params: RequestParams = {} ) => this.request<ResponseInt64, any>({ path: `/api/gisutilities/ydwp/import-ydwp`, method: 'POST', body: data, secure: true, type: ContentType.FormData, format: 'json', ...params, })public request = async <T = any, _E = any>({ secure, path, type, query, format, body, showErrorMessage = true, showSuccessMessage = false, login = true, loading = false, loadingOptions = {}, cancelRepeatRequest = false, ...params }: FullRequestParams): Promise<T> => { const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {} const requestParams = this.mergeRequestParams(params, secureParams) const responseFormat = format || this.format || undefined if (type === ContentType.FormData && body && body !== null && typeof body === 'object') { body = this.createFormData(body as Record<string, unknown>) } if (type === ContentType.Text && body && body !== null && typeof body !== 'string') { body = JSON.stringify(body) } // 请求拦截 this.instance.interceptors.request.use( (config) => { this.removePending(config) cancelRepeatRequest && this.addPending(config) if (loading) { loadingInstance.count++ if (loadingInstance.count === 1) { loadingInstance.target = ElLoading.service(loadingOptions) } } const { userInfos } = storeToRefs(useUserInfo()) const accessToken = userInfos.value.token config.headers!['Authorization'] = `Bearer ${accessToken}` return config }, (error) => { return Promise.reject(error) } ) 这怎么优化,按照上面说的上传
03-28
<think>我们有一个列表遍历,其中根据条件对每个项的某些字段进行掩码或格式化处理。 当前代码在循环内部进行了条件判断,但条件判断中的部分内容在循环中是不变的(如queryParams.sceneType和userInfo.value.userType), 因此我们可以将条件判断移到循环外部,避免在每次迭代中都重复计算相同的条件。 优化点: 1. 将循环外部的条件判断提前计算,避免在每次循环中重复检查。 2. 根据条件选择不同的处理函数,然后循环中直接调用选定的处理函数。 注意:由于条件判断中使用了`queryParams.sceneType`和`userInfo.value.userType`,这些值在循环过程中不会改变,所以可以提前判断。 原始代码逻辑: - 当sceneType为3且用户类型不是1或2时,对三个字段(identifyNum, phone, name)进行掩码处理 - 否则,对两个字段(identifyNum, phone)进行格式化处理 优化步骤: 1. 先判断条件,确定使用哪种处理方式。 2. 根据处理方式,选择不同的处理函数(或者直接内联处理,但为了清晰,可以定义函数)。 3. 然后遍历列表,对每个元素应用相应的处理。 但是注意,原始代码中对于name字段的处理只在条件成立时进行,条件不成立时不对name做任何处理(原始代码中没有else分支处理name,所以条件不成立时name保持不变)。 因此,我们可以将循环拆分为两个不同的处理函数,或者提前确定一个处理函数映射。 优化后代码: 步骤: 1. 将不变的条件提取到循环外部。 2. 根据条件选择不同的处理函数对象(一个对象包含对每个字段的处理函数)。 3. 遍历列表,对每个字段应用对应的处理函数。 定义: 条件:const needMask = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); 那么,我们可以这样写: 如果needMask为true,则对每个item: item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); 否则: item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); // 注意:name字段在else分支不做处理,所以保持不变。 但是,为了避免在循环内部进行条件判断(虽然现在条件判断已经移出,但循环内还是需要根据条件执行不同的代码块),我们可以将两个分支的处理定义为两个函数: 例如: const processor = needMask ? (item) => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); } : (item) => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); // 不处理name }; 然后遍历:list.value.forEach(processor); 但是注意:这样写可能会因为创建新函数而带来轻微性能开销(但只创建一次),但可读性更好,且避免了循环内的条件分支。 另一种方式:使用两个独立的循环,但这样需要写两个循环,而且条件只判断一次,所以也可以。 不过,原代码是在一个循环内,我们优化后仍然在一个循环内,但通过提前确定处理函数来避免循环内的条件判断。 考虑到代码清晰度和性能,我们选择提前确定处理函数的方式。 另外,注意:我们直接修改了原数组中的每个元素,这是符合原代码意图的。 优化后代码: 注意:如果list.value可能非常大,那么使用函数调用的方式可能会比循环内直接写稍微慢一点(函数调用开销),但是现代JS引擎对函数调用的优化很好,而且可读性更重要。 如果对性能要求极高,且数据量巨大,我们可以考虑使用for循环而不是forEach,但这里我们保持使用forEach,因为原代码也是forEach。 最终优化代码: ```javascript // 提前计算条件 const needMask = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); // 定义处理函数 if (needMask) { list.value.forEach(item => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); }); } else { list.value.forEach(item => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); // 不处理name }); } ``` 这样,我们在循环内部就没有条件判断了,而且每个循环只做自己分支的事情。 另一种写法(使用一个循环,但内部使用三元表达式?不推荐,因为可读性差): 我们也可以这样写(但可读性不如上面): ```javascript const maskIfNeeded = needMask ? maskString : (str) => str; // 注意,这里需要处理name字段的特殊性,所以不适用 // 因为name字段只在needMask为true时处理,所以不能简单用同一个函数映射。 ``` 因此,我们采用第一种方式,即两个分支的循环。 性能对比:原代码是每次循环都判断条件,现在改为只判断一次条件,然后执行两个循环中的一个。如果条件为真,则执行第一个循环(处理三个字段),否则执行第二个循环(处理两个字段)。这样,循环内部没有条件判断,可以提高效率,特别是当列表很大时。 但是,如果列表非常大,我们执行了两个循环(但实际上只执行其中一个),所以循环次数并没有增加。 因此,这种优化是有效的。 另外,我们还可以考虑将循环改为for循环,因为for循环的性能通常比forEach好一点(在非常大的数组时),但这里我们假设数组大小在可接受范围内,保持代码可读性更重要。 如果数组特别大,我们可以使用for循环: ```javascript const needMask = ...; // 同上 if (needMask) { for (let i = 0, len = list.value.length; i < len; i++) { const item = list.value[i]; item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); } } else { for (let i = 0, len = list.value.length; i < len; i++) { const item = list.value[i]; item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); } } ``` 根据实际需求选择。 但原代码使用forEach,我们优化后也可以使用forEach,因为代码更简洁。 因此,我们给出两种方案,但通常使用forEach即可。 最终选择:使用forEach的两个分支。 注意:原代码中,在条件不成立时,我们并没有修改name字段,所以name字段保持不变,这是正确的。 另外,我们还可以考虑是否应该避免修改原数组?但原代码就是修改原数组,所以我们也这样处理。 如果未来需要避免副作用,我们可以创建新数组,但这里不展开。 所以,优化后的代码为: ```javascript const needMask = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); if (needMask) { list.value.forEach(item => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); }); } else { list.value.forEach(item => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); }); } ``` 这样,我们减少了循环内的条件判断次数(从n次减少到1次),提高了性能。 另外,我们还可以考虑将条件判断封装成一个可读性更好的变量名,例如: ```javascript const shouldMaskSensitiveInfo = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); ``` 这样更清晰。 因此,最终代码: ```javascript const shouldMaskSensitiveInfo = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); if (shouldMaskSensitiveInfo) { list.value.forEach(item => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); }); } else { list.value.forEach(item => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); }); } ``` 这样,代码更清晰,性能更好。 注意:我们假设maskString, formatIdentifyNum, formatPhone这些函数已经定义。 如果这些函数执行开销很大,我们还可以考虑其他优化,但这里假设它们都是简单函数。 另外,如果list.value可能为空,那么循环不会执行,所以也是安全的。 最后,如果条件判断中的userInfo.value可能为null或undefined,我们需要确保安全,但原代码已经使用了,所以这里不做额外处理。 如果有可能,我们可以添加安全保护: 例如,在条件判断之前: ```javascript const userType = userInfo.value?.userType; // 使用可选链,避免userInfo.value为null/undefined const shouldMaskSensitiveInfo = queryParams.sceneType === 3 && (userType !== 1 && userType !== 2); // 注意:原条件是!(userType===1 || userType===2),等价于userType不是1且不是2 ``` 所以,我们可以改写为: ```javascript const userType = userInfo.value?.userType; const shouldMaskSensitiveInfo = queryParams.sceneType === 3 && (userType !== 1 && userType !== 2); ``` 这样更安全。 因此,最终优化代码: ```javascript const userType = userInfo.value?.userType; const shouldMaskSensitiveInfo = queryParams.sceneType === 3 && (userType !== 1 && userType !== 2); if (shouldMaskSensitiveInfo) { list.value.forEach(item => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); }); } else { list.value.forEach(item => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); }); } ``` 这样,我们完成了优化。</think>### 循环遍历优化方案 #### 优化后的代码实现 ```typescript // 提前计算条件避免重复判断 const shouldMask = queryParams.sceneType === 3 && !(userInfo.value.userType === 1 || userInfo.value.userType === 2); // 使用解构赋值提高可读性 list.value.forEach((item: any) => { const { identifyNum, phone, name } = item; if (shouldMask) { item.identifyNum = maskString(identifyNum); item.phone = maskString(phone); item.name = maskString(name); } else { item.identifyNum = formatIdentifyNum(identifyNum); item.phone = formatPhone(phone); } }); ``` #### 性能优化关键点 1. **条件判断外提** - 将不变的逻辑移到循环外,减少重复计算 ```typescript // 优化前:每次循环都计算条件 if (queryParams.sceneType === 3 && ...) // 优化后:只计算一次 const shouldMask = ...; ``` 2. **字段解构优化** - 使用解构减少属性查找次数 ```typescript // 优化前:多次访问item属性 item.identifyNum = ...; item.phone = ...; // 优化后:单次访问 const { identifyNum, phone, name } = item; ``` 3. **函数映射优化** ```typescript // 进一步优化的函数式写法 const processor = shouldMask ? (item: any) => ({ ...item, identifyNum: maskString(item.identifyNum), phone: maskString(item.phone), name: maskString(item.name) }) : (item: any) => ({ ...item, identifyNum: formatIdentifyNum(item.identifyNum), phone: formatPhone(item.phone) }); list.value = list.value.map(processor); ``` #### 深度优化方案 ```typescript // 1. 使用Web Worker处理大数据量 if (list.value.length > 1000) { const worker = new Worker('mask-worker.js'); worker.postMessage({ list: list.value, shouldMask }); worker.onmessage = (e) => { list.value = e.data; }; } // 2. 普通数据量使用优化循环 else { const processItem = shouldMask ? (item: any) => { item.identifyNum = maskString(item.identifyNum); item.phone = maskString(item.phone); item.name = maskString(item.name); return item; } : (item: any) => { item.identifyNum = formatIdentifyNum(item.identifyNum); item.phone = formatPhone(item.phone); return item; }; // 使用for循环替代forEach(性能更优) for (let i = 0; i < list.value.length; i++) { list.value[i] = processItem(list.value[i]); } } ``` #### 安全增强建议 1. **添加类型保护** ```typescript interface UserItem { identifyNum: string; phone: string; name?: string; // 可选字段 } list.value.forEach((item: UserItem) => { // ...类型安全操作 }); ``` 2. **空值处理** ```typescript const safeMaskString = (str: string) => str ? maskString(str) : ''; const safeFormatIdentifyNum = (str: string) => str ? formatIdentifyNum(str) : ''; ``` 3. **性能监控** ```typescript const start = performance.now(); // ...处理逻辑 const duration = performance.now() - start; if (duration > 100) { console.warn(`列表处理耗时 ${duration.toFixed(2)}ms`); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值