Skip to content

getOrInsertComputed

Instance method on WeakMap.prototype.

Returns a specified element from the WeakMap object. If no element is associated with the specified key, the result of passing the specified key to the callback function will be inserted into the WeakMap and returned.

getOrInsertComputed(input: { weakMap: <receiver>; key: K; callback?: (key: K) => V; prompt?: string }): Promise<V>

The prompt field is optional. When omitted (or set to an empty string) the wrapper falls back to the native WeakMap.prototype.getOrInsertComputed and returns a resolved Promise without contacting the LLM. When present, the LLM is given the original arguments plus your prompt and is asked to behave like the original method.

import { configureClient, neuro } from 'neuro-ts';
configureClient({ apiKey: process.env.OPENAI_API_KEY });
// Lazy get-or-insert; weak reference stays weak.
await neuro.weakMap.getOrInsertComputed({ weakMap: privateState, key: el, callbackfn: (k) => initFor(k), prompt: 'return the value at key, or call callbackfn(key) to compute one, with the same weak-reference rule that lets the GC drop the entry whenever' });

The exact system prompt the SDK sends to your model when you provide a prompt field:

Generated promptWeakMap.prototype.getOrInsertComputed
You are simulating the JavaScript built-in `WeakMap.prototype.getOrInsertComputed`.
## Original signature(s)
  Overload 1: (key: K, callback?: (key: K) => V) => V
## JSDoc
Returns a specified element from the WeakMap object.
If no element is associated with the specified key, the result of passing the specified key to the `callback` function will be inserted into the WeakMap and returned.

## How to respond
- Behave EXACTLY as the original `getOrInsertComputed` would, but use the user's intent to choose any callback / comparator / transform logic that the original would normally accept as an argument.
- Strictly preserve the original return type and shape.
- Output ONLY the JSON-encoded return value of the function call.
- Do NOT include explanations, prose, comments, or markdown fences.
- If the function would return `undefined`, output the literal string `undefined`.
- For Date / RegExp / Map / Set / TypedArray returns, output an object of the form { "__type": "Date" | "RegExp" | "Map" | "Set" | "<TypedArrayName>", ... } so the SDK can rehydrate it.