UNPKG

@truenewx/tnxcore

Version:

互联网技术解决方案:JavaScript核心扩展支持

71 lines (63 loc) 1.9 kB
/** * 属性集处理类 */ export default class Properties { #values: Record<string, string> = {}; constructor(content?: string | Record<string, string>) { if (content) { if (typeof content === 'string') { let lines = content.split('\n'); for (let line of lines) { let index = line.indexOf('='); if (index > 0) { let key = line.substring(0, index).trim(); let value = line.substring(index + 1).trim(); this.#values[key] = value.trim(); } } } else if (typeof content === 'object') { Object.assign(this.#values, content); } } } /** * 获取值 * @param key 键 * @return {String} 值 */ get(key: string): string { return this.#values[key]; } /** * 设置值 * @param {String} key 键 * @param {String} value 值 */ set(key: string, value: string): void { if (value && typeof value === 'string') { value = value.trim(); } this.#values[key] = value; } /** * 仅当值不存在时设置 * @param {String} key 键 * @param {String} value 值 * @returns {boolean} 是否设置成功 */ setIfAbsent(key: string, value: string): boolean { let v = this.get(key); if (v === undefined || v === null) { this.set(key, value); return true; } return false; } toString(): string { let lines: string[] = []; for (let key in this.#values) { lines.push(key + '=' + this.#values[key]); } return lines.join('\n') + '\n'; } }