Map Merge Resolves Conflicting Keys
Concatenating map entries lets later layers win, and a resolveConflict callback upgrades the merge into a per-key policy for layered configuration.
Code
// Layered config: defaults < user settings. Later layers win on
// conflicting keys when the maps are concatenated in order.
const defaults = new Map([
['timeout', 5000],
['retries', 2],
['endpoint', '/api'],
]);
const userSettings = new Map([
['retries', 5],
['endpoint', '/api/v2'],
]);
// Spread concatenates [key, value] pairs; later entries overwrite earlier ones.
const merged = new Map([...defaults, ...userSettings]);
console.log('last wins:', merged.get('retries'), merged.get('endpoint'));
// A policy hook decides each conflicting key instead of blind overwrite.
function mergeMaps(layers, resolveConflict) {
const result = new Map();
for (const layer of layers) {
for (const [key, value] of layer) {
if (result.has(key)) {
result.set(key, resolveConflict(key, result.get(key), value));
} else {
result.set(key, value);
}
}
}
return result;
}
// Keep the larger retry count, but always take the newest endpoint.
const policy = mergeMaps([defaults, userSettings], (key, current, incoming) =>
key === 'retries' ? Math.max(current, incoming) : incoming
);
console.log('policy: ', policy.get('retries'), policy.get('endpoint'));
console.log('merged keys:', [...merged.keys()]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
last wins: 5 /api/v2
policy: 5 /api/v2
merged keys: [ 'timeout', 'retries', 'endpoint' ]What the code does
The code’s whole job belongs to the function mergeMaps.
The core work runs in nested loops — outer for (const layer of layers), inner for (const [key, value] of layer).
Points of care
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
Entry signature: function mergeMaps(layers, resolveConflict)
The demo output is labeled (last wins:, policy:, merged keys:), so every printed line maps back to its originating operation.
Key statements
const merged = new Map([...defaults, ...userSettings]);
const result = new Map();
const policy = mergeMaps([defaults, userSettings], (key, current, incoming) =>
key === 'retries' ? Math.max(current, incoming) : incoming
);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `mergeMaps` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.