Skip to content

Instantly share code, notes, and snippets.

@LeaVerou
Last active November 23, 2020 09:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LeaVerou/2881cc634df29c9d1c89fcb965f699f0 to your computer and use it in GitHub Desktop.
Save LeaVerou/2881cc634df29c9d1c89fcb965f699f0 to your computer and use it in GitHub Desktop.
Insert a property before another object literal property, while maintaining all references to that object
function insert(obj, {before, property, value}) {
let found, temp = {};
// Delete all properties from before onwoards and save them in temp
for (let p in obj) {
if (p === before) {
found = true;
}
if (found) {
temp[p] = obj[p];
delete obj[p];
}
}
// Add new property
obj[property] = value;
// Re-add removed properties
for (let p in temp) {
obj[p] = temp[p];
}
}
function insert(obj, {before, property, value}) {
let found, temp = {};
// Delete all properties from before onwoards and save them in temp
for (let p in obj) {
if (p === before) {
found = true;
}
if (found) {
temp[p] = obj[p];
delete obj[p];
}
}
// Add new property and re-add removed properties
Object.assign(obj, {property: value, ...temp});
}
function insert(obj, {before, property, value}) {
// Create a copy of entries and add the new property in place
let entries = Object.entries(obj);
let i = entries.findIndex(a => a[0] === before);
entries.splice(i, 0, [property, value]);
// Delete all obj properties
for (let p in obj) {
delete obj[p];
}
// Re-add with the new one
Object.assign(obj, Object.fromEntries(entries));
}
@monfera
Copy link

monfera commented Nov 23, 2020

@pygy rolling your own code not fundamentally difficult, but finding the somewhat optimal set of tick values (so they're nice round numbers, and not too many ticks and not to few) and scale nicing etc. can get labor intensive, has edge cases too. Btw. there's no need to import the entirety of D3; it's enough to import d3-scale, although the last time I checked, one still ends up with color palette arrays etc. which you wouldn't use. Therefore even d3-scale is very large if you need it for just one cartesian scale. Not sure if Svelte-style JS treeshaking can get rid of the palettes etc. now, I think, worth a try, interested if you do that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment