Last active
September 25, 2023 17:18
-
-
Save mflorida/19d0a53a0ba573eed037e3ee6ada94fd to your computer and use it in GitHub Desktop.
Insert new item into a Map object after specified key.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Insert 'insert' 2-D array after 'after' key in 'map' | |
* WARNING: THIS MUTATES THE ORIGINAL Map! | |
* @param {Map} map - Map to insert into | |
* @param {any} after - key to insert after | |
* @param {[any, any]} insert - 2-D array for entry to insert | |
* @returns {Map} - returns mutated 'map' passed as first argument | |
*/ | |
function insertAfterKey(map, after, insert){ | |
const [insertKey, insertValue] = insert; | |
// Copy to temp Map before clearing | |
const tmp = new Map(map); | |
// Remove all entries, but keep the reference | |
map.clear(); | |
// Iterate 'tmp' and copy entries back to original reference | |
for (const [key, value] of tmp) { | |
map.set(key, value); | |
// If the current key matches 'after'... | |
if (key === after) { | |
// ...insert the new item | |
map.set(insertKey, insertValue); | |
} | |
} | |
// If item is not yet inserted (there's no key that matches 'after')... | |
if (!map.has(insertKey)) { | |
// Insert item at the end | |
map.set(insertKey, insertValue); | |
} | |
// Return same Map reference that was passed to the function | |
return map; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment