【问题标题】:ES6 Map or array: need first, last, previuos, next, get (mixing array and Map) in TypeScriptES6 Map 或数组:TypeScript 中需要 first、last、previous、next、get(混合数组和 Map)
【发布时间】:2016-08-17 07:40:45
【问题描述】:

我正在使用 ES6 Map 对象,其中键是符号、数字或字符串。我选择 map over array 是因为我经常按 key 搜索项目,并且不想每次需要查找 key 时都遍历 array。它也适合我的键值模式。
还会有很多我需要下一个和上一个项目的操作, 偶尔是第一次和最后一次。
基本上它代表表格的表格。
目前我使用:

  • next:遍历Map.keys(),直到找到当前并返回下一个
  • 上一页:遍历Map.keys()记住最后一个键,找到当前返回最后一个键
  • 第一:Map.keys().next().value
  • 最后:Array.from(this._data.keys()).reverse()[0];

最后的其他想法是:

let lastKey: any;  //I am using TypeScript with "noImplicitAny": true
for (lastKey of map.keys()) { }

哪个更好?

还有其他可能的解决方案吗?我也在考虑创建具有数组和映射的新对象,但这似乎很多或可能没有?像这样的:

class MapArray
{
    map = new Map<string | number | symbol, number>();  //map between keys and array indexes
    array: Array<any> = [];

    constructor(data: Array<any>)
    {
        for (const d in data)
        {
            this.add(d);
        }
    }

    add(value: any)
    {
        this.array.push(value);
        this.map.set(Symbol(), this.array.length - 1);
    }

    next(currentKey: symbol)
    {
        const current = this.map.get(currentKey);

        if (typeof current !== "undefined")
        {
            if (current >= this.array.length - 1)
                return null;    //current is last item
            return this.array[current + 1];
        }
        return this.array[0];   //return first
    }

    previous(currentKey: symbol)
    {
        const current = this.map.get(currentKey);

        if (typeof current !== "undefined")
        {
            if (current == 0)
                return null;    //current is first item
            return this.array[current - 1];
        }
        return this.array[this.array.length - 1];       //return last
    }

    get(key: symbol)
    {
        const index = this.map.get(key);
        if (typeof index !== "undefined")
            return this.array[index];
        return null;
    }

    set(key: symbol, value: any)
    {
        const index = this.map.get(key);
        if (typeof index !== "undefined")
            this.array[index] = value;
        else
            this.add(value);
    }
    //TODO write delete
    //TODO write first/last
    //TODO write generator
}

你怎么看?数据通常是小数组(20 项具有 3 个属性的对象)或具有大数据的更大数组(1000 项具有 100 个或更多属性的对象)。
代码将主要在移动设备上运行,因此内存使用和性能很重要。

【问题讨论】:

  • 结构中的对象有多少属性并不重要。
  • "最后的其他想法" ...好多了。它不需要实例化数组或移动东西 (reverse)。当然,它仍然非常低效,但至少在内存上没有。
  • 你真的需要delete吗?并且:这种情况经常发生吗?
  • 尚不确定是否删除。我们会看到项目何时增长,但目前不需要删除方法。
  • 那么您的MapArray 确实是最好的解决方案。

标签: javascript arrays dictionary ecmascript-6


【解决方案1】:

我也在考虑创建一个具有 Array 和 Map 的新类,但这似乎太多了?

不,这是正确的做法。这是为索引访问获得合理性能的唯一选择。

您正在使用的所有操作的抽象总是很有帮助的。您可以将实现换成更简单(足够时)或更复杂(需要时)的实现,而无需更改使用该结构的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2021-12-27
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多