js-set-map-lookups

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Use Set/Map for O(1) Lookups

使用Set/Map实现O(1)时间复杂度查找

Convert arrays to Set/Map for repeated membership checks.
Incorrect (O(n) per check):
typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
Correct (O(1) per check):
typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
将数组转换为Set/Map以进行重复的成员资格检查。
错误示例(每次查找时间复杂度O(n)):
typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
正确示例(每次查找时间复杂度O(1)):
typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))