Recursive AI

Initialize a JavaScript Map value only when a key is missing

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

getOrInsertComputed() runs your function only for a missing key.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const labels = new Map(); let calls = 0;
const get = () => labels
  .getOrInsertComputed('tea', () => ++calls);
`${get()}, ${get()}; calls: ${calls}`;
""").AsString);

Unzip the example, then dotnet run.

Prints the same value twice, with just one initializer call:

Text
1, 1; calls: 1

The full program

The download starts with tea already in the map and looks up coffee twice. The count shows exactly which lookup calls the initializer.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const labels = new Map([['tea', 'Tea']]);
let calls = 0;
const makeLabel = key => {
  calls++;
  return key.toUpperCase();
};
const lines = [];
for (const key of ['tea', 'coffee', 'coffee']) {
  const value = labels.getOrInsertComputed(key, makeLabel);
  lines.push(`${key}: ${value} (initializer calls: ${calls})`);
}
lines.push(`entries: ${labels.size}`);
lines.join('\n');
""").AsString);
Text
tea: Tea (initializer calls: 0)
coffee: COFFEE (initializer calls: 1)
coffee: COFFEE (initializer calls: 1)
entries: 2

If the initializer throws, the error propagates and getOrInsertComputed() does not store a result for that call.

Variations

Use a default value you already have. Replace the JavaScript inside Evaluate:

JAVASCRIPT
const counts = new Map([['tea', 3]]);
const tea = counts.getOrInsert('tea', 0);
const coffee = counts.getOrInsert('coffee', 0);
`tea: ${tea}; coffee: ${coffee}`;
Text
tea: 3; coffee: 0

The short answer

Call map.getOrInsertComputed(key, initializer) when you want to compute a value only on a miss. The method passes the missing key to the initializer, stores what it returns, and returns that value to the caller. On a hit, it just returns the stored value. OneEcma includes this ES2026 Map method. Outside OneEcma, getOrInsert() and getOrInsertComputed() work in Chrome and Edge 145+, Firefox 144+, Safari 26.2+, and Node.js 26.0.0+; use the has()/get()/set() fallback below on older versions.

How do you get a Map value by key in JavaScript?

Use map.get(key) if you only want to read. It returns undefined when the key is absent, but also when you’ve deliberately stored undefined. Use map.has(key) when that distinction matters. getOrInsertComputed() checks for an entry, not for a truthy value: an existing undefined, null, false, or 0 still counts as a hit. Testing map.get(key) for truthiness would replace some of those values even though the key is already there.

What’s the difference between getOrInsert() and getOrInsertComputed()?

Use getOrInsert() with a value you already have, like the starting count 0 above. JavaScript evaluates arguments before calling the method, so passing the result of an initializer to getOrInsert() runs that initializer even on a hit. With getOrInsertComputed(), pass the function itself. The method invokes it only when it has to insert a value.

For a runtime that doesn’t have the method, use has(), set(), and get(). Here’s a replacement script for the call at the top:

JAVASCRIPT
const labels = new Map([['tea', undefined]]);
let calls = 0;
function get(key) {
  if (!labels.has(key)) {
    calls++;
    labels.set(key, key.toUpperCase());
  }
  return labels.get(key);
}
`${get('tea')}, ${get('coffee')}; calls: ${calls}`;
Text
undefined, COFFEE; calls: 1

The test on has() preserves the explicitly stored undefined for tea. Only the new coffee key triggers initialization.

All oneecma recipes