面试题答案
一键面试设计思路
- 创建可配置的货币转换管道:
- 定义一个货币转换管道,该管道接受多个配置参数,如货币符号位置、小数位数、千位分隔符样式等。这样可以根据不同用户需求灵活配置,避免重复代码。
- 使用
@Pipe
装饰器来创建管道,并在transform
方法中实现具体的转换逻辑。
- 缓存计算结果:
- 为了减少不必要的管道计算,可以在管道内部缓存计算结果。通过记录上一次的输入值和配置参数,当相同的输入再次出现时,直接返回缓存的结果,而不需要重新计算。
- 依赖注入:
- 如果货币转换需要依赖一些外部服务(如汇率获取服务),使用Angular的依赖注入机制来提供这些服务,使管道更加可测试和可维护。
关键代码示例
- 创建货币转换管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencyFormat',
pure: false // 设置为不纯管道,以便在输入值或配置变化时重新计算
})
export class CurrencyFormatPipe implements PipeTransform {
private cache: { [key: string]: string } = {};
transform(
value: number,
currencySymbol: string = '$',
symbolPosition: 'before' | 'after' = 'before',
decimalDigits: number = 2,
thousandSeparator: string = ','
): string {
const cacheKey = `${value}-${currencySymbol}-${symbolPosition}-${decimalDigits}-${thousandSeparator}`;
if (this.cache[cacheKey]) {
return this.cache[cacheKey];
}
const numberPart = value.toFixed(decimalDigits).split('.');
const integerPart = numberPart[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
const decimalPart = numberPart[1];
const formattedValue = symbolPosition === 'before'? `${currencySymbol}${integerPart}.${decimalPart}` : `${integerPart}.${decimalPart}${currencySymbol}`;
this.cache[cacheKey] = formattedValue;
return formattedValue;
}
}
- 在模板中使用管道:
<div>
<p>货币金额: {{ amount | currencyFormat:'€': 'after': 3: '.' }}</p>
</div>
在上述代码中,amount
是组件中的货币数值,通过 currencyFormat
管道按照指定的货币符号(€
)、符号位置(after
)、小数位数(3
)和千位分隔符(.
)进行格式化显示。同时,管道通过缓存机制减少了重复计算。