Set.has Answers Repeated Membership Checks

Move repeated membership checks from Array.prototype.includes to a Set built once, turning every lookup into a hash hit with case normalized at the boundary.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
const allowed = ["png", "jpg", "gif", "webp", "avif"];
const uploads = ["png", "exe", "webp", "PNG", "svg", "jpg", "gif"];

// 每次都用 includes:数组线性扫描,检查次数越多代价越大
for (const ext of uploads) {
  console.log(`includes: ${ext} -> ${allowed.includes(ext)}`);
}

// 反复做成员检查时把成员收进 Set:has 是一次哈希查找
// membership 判断在边界处统一小写归一化,语义不变
const allowedSet = new Set(allowed.map((ext) => ext.toLowerCase()));
for (const ext of uploads) {
  console.log(`set.has: ${ext} -> ${allowedSet.has(ext.toLowerCase())}`);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

includes: png -> true
includes: exe -> false
includes: webp -> true
includes: PNG -> false
includes: svg -> false
includes: jpg -> true
includes: gif -> true
set.has: png -> true
set.has: exe -> false
set.has: webp -> true
set.has: PNG -> true
set.has: svg -> false
set.has: jpg -> true
set.has: gif -> true

How the snippet works

Everything operates on top-level bindings: allowed, uploads, allowedSet.

Caveats

  • Zero third-party dependencies — the runtime provides every API used here.

Applying it

Expect labeled output — includes: $, set.has: $ — when the file runs.

Statements that matter

const allowedSet = new Set(allowed.map((ext) => ext.toLowerCase()));

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `allowed`, `uploads`, `allowedSet`.