我正在使用 ES6 Map 对象,其中的键是符号、数字或字符串。我选择 map over array 是因为我经常按键搜索项目,并且不想每次需要查找键时都遍历数组。它也适合我的键值模式。
还会有很多操作,我需要下一个和上一个项目,
偶尔第一个和最后一个。
基本上它代表了 Table for Grid。
目前我使用:
- next:遍历
Map.keys()
直到找到 current 并返回 next - previous:遍历
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()) { }
哪个更好?
还有其他可能的解决方案吗?我也在考虑创建具有数组和 Map 的新对象,但这似乎很多或可能没有?像这样:
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 或更多属性的对象)。
代码将主要在手机上运行,因此内存使用和性能很重要。
最佳答案
I was also thinking of creating a new class which would have Array and Map, but this seems to much?
不,这是正确的做法。这是为索引访问获得合理性能的唯一选择。
您正在使用的所有操作的抽象总是有帮助的。您可以将实现替换为更简单(当它足够时)或更精细(当您需要时)的实现,而无需更改使用该结构的代码。
关于javascript - ES6 Map 或 array : need first, last, previous, next, 在 TypeScript 中获取(混合数组和 Map),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38990778/