/** ***************************************** * Created by edonet@163.com * Created on 2021-03-28 15:49:43 ***************************************** */ 'use strict'; /** ***************************************** * 索引对象 ***************************************** */ export class Indexed { /** 索引映射 */ private $$indexedMap!: Record; /** 索引列表 */ private $$indexedList!: string[]; /** 初始化对象 */ public constructor(list?: string[], map?: { [key: string]: number }) { // 定义索引映射 Object.defineProperty(this, '$$indexedMap', { configurable: false, enumerable: false, writable: false, value: {}, }); // 定义索引列表 Object.defineProperty(this, '$$indexedList', { configurable: false, enumerable: false, writable: false, value: [], }); // 添加列表 if (list && list.length) { list.forEach(val => this.add(val)); } // 添加映射 if (map) { Object.keys(map).forEach(key => { const value = map[key]; // 添加映射 if (!(key in this.$$indexedMap)) { this.$$indexedMap[key] = value; } // 添加到列表 if (this.$$indexedList[value] === undefined) { this.$$indexedList[value] = key; } }); } } /** 添加值 */ public add(value: string): void { this.$$indexedMap[value] = this.$$indexedList.length; this.$$indexedList.push(value); } /** 设置索引 */ public set(value: string, index: number): void { this.$$indexedMap[value] = index; } /** 获取值 */ public get(index: number): string { return this.$$indexedList[index]; } /** 获取索引 */ public indexOf(value: string): number { return this.$$indexedMap[value]; } }