-
-
Save getify/9b3bdb93da7f31702ddc593bfc6aba32 to your computer and use it in GitHub Desktop.
insert object keys in order, enumerate them in order
This file contains 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
var obj = { a: 1, b: 2, c: 3, d: 4 }; | |
insert(obj,{ property: "g", value: 7 }); | |
insert(obj,{ before: "g", property: "e", value: 5 }); | |
insert(obj,{ property: "h", value: 8 }); | |
insert(obj,{ before: "g", property: "f", value: 6 }); | |
obj.i = 9; | |
console.log(keys(obj)); | |
// [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ] | |
delete obj.g; | |
console.log(keys(obj)); | |
// [ "a", "b", "c", "d", "e", "f", "h", "i" ] |
This file contains 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
var { insert, keys } = (function define(){ | |
var keyStore = new WeakMap(); | |
return { insert, keys }; | |
function insert(obj,{ before = "", property, value }){ | |
registerKeys(obj); // this is optional for safety/flexibility... | |
obj[property] = value; | |
if (!keyStore.has(obj)) { | |
keyStore.set(obj,[]); | |
} | |
var keyOrder = keyStore.get(obj); | |
var beforeIdx = keyOrder.findIndex(k => k === before); | |
if (beforeIdx >= 0) { | |
keyOrder.splice(beforeIdx,0,property); | |
} | |
else { | |
keyOrder.push(property); | |
} | |
} | |
function keys(obj) { | |
registerKeys(obj); // this is optional for safety/flexibility... | |
return [ ...(keyStore.get(obj) || []) ]; | |
} | |
// this is optional for safety/flexibility... | |
function registerKeys(obj) { | |
var objKeys = Object.keys(obj); | |
var knownKeys = keyStore.get(obj) || []; | |
keyStore.set(obj,knownKeys); | |
if (objKeys.length > 0) { | |
if (knownKeys.length > 0) { | |
// have any keys been removed from the object? | |
for (let [idx,key] of knownKeys.entries()) { | |
if (!objKeys.includes(key)) { | |
knownKeys.splice(idx,1); | |
} | |
} | |
// are there any newly-discovered keys in the object? | |
for (let [idx,key] of objKeys.entries()) { | |
if (!knownKeys.includes(key)) { | |
knownKeys.push(key); | |
} | |
} | |
} | |
else { | |
knownKeys.push(...objKeys); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment