1. 概述
《JavaScript高级程序设计》对string(字符串)有如下描述:ECMAScript中的字符串是不可变的(immutable),意思是一旦创建,它们的值就不能变了。要修改某个变量中的字符串值,必须先销毁原始的字符串,然后将包含新值的另一个字符串保存到该变量。
所以在JavaScript/TypeScript中,使用string拼接大量字符串,会产生性能问题。StringBuilder就是为了解决大量字符串拼接而开发的。
2. 实现原理
- 将字符串保存于Array,最后使用Array.join函数拼接所有字符串。
- 利用TypeScript函数重载机制,支持多中数据类型的添加,StringBuilder会自动将不是string类型的数据转换为string。
3. 代码实现
export class StringBuilder {
private _store: Array<string>;
constructor();
constructor(value: string);
constructor(value: number);
constructor(value: boolean);
constructor(value: string[]);
constructor(value: StringBuilder);
constructor(value?: string | number | boolean | string[] | StringBuilder) {
if (typeof value === 'string') {
this._store = [value];
} else if (value instanceof Array) {
this._store = value;
} else if (value instanceof StringBuilder) {
this._store = value._store;
} else if (value) {
this._store = [value.toString()];
} else {
this._store = [];
}
}
get length() {
return this._store.length;
}
append(value: string): void;
append(value: number): void;
append(value: boolean): void;
append(value: string[]): void;
append(value: StringBuilder): void;
append(value: string | number | boolean | string[] | StringBuilder): void {
if (typeof value === 'string') {
this._store.push(value);
} else if (value instanceof Array) {
this._store.push(...value);
} else if (value instanceof StringBuilder) {
this._store.push(...value._store);
} else {
this._store.push(value.toString());
}
}
insert(index: number, value: string): void;
insert(index: number, value: number): void;
insert(index: number, value: boolean): void;
insert(index: number, value: string[]): void;
insert(index: number, value: StringBuilder): void;
insert(index: number, value: string | number | boolean | string[] | StringBuilder): void {
if (typeof value === 'string') {
this._store.splice(index, 0, value);
} else if (value instanceof Array) {
this._store.splice(index, 0, ...value);
} else if (value instanceof StringBuilder) {
this._store.splice(index, 0, ...value._store);
} else {
this._store.splice(index, 0, value.toString());
}
}
clear() {
this._store = [];
}
remove(start: number, length: number) {
this._store.splice(start, length);
}
replace(substr: string, replacement: string) {
this._store = this._store.map(s => s === substr ? replacement : s);
}
toString() {
return this._store.join('');
}
equals(value: StringBuilder) {
return this.toString() === value.toString();
}
}
4. 源码地址:
- 项目地址: Armon/string-builder
- 作者: Armon