Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created August 4, 2019 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/fda0adb241db2bfa5cb6e6c85b47b11e to your computer and use it in GitHub Desktop.
Save dfkaye/fda0adb241db2bfa5cb6e6c85b47b11e to your computer and use it in GitHub Desktop.
insert-at - exercise in es5
// 4 Aug 2019
// prompted by
// https://www.linkedin.com/posts/sifat-haque-9a3028b1_javascript-simpleabrjavascript-coding-activity-6561302165493780480-6A1F
// Here is an way to insert a new item to an Object at any specific position.
function insertAt(obj, key, value, at) {
if (Array.isArray(obj)) {
var a = obj.slice();
at === +at ? a.splice(at, 0, value) : a[at] = value;
return a;
}
var newObj = {};
var keys = Object.keys(obj);
keys.splice(at, 0, key);
keys.forEach(function(k) {
newObj[k] = k === key ? value : obj[k];
});
return newObj;
}
// objects
var o = { 'q': 'bert', 'a': 'way'}
console.log( insertAt(o, 'x', 'x', 1) );
console.log( insertAt(o, 'email', 'something', 1) );
// Arrays
var a = ['3', 'b', 0 ];
console.log( insertAt(a, 1, 'one', 1) ) // index
console.log( insertAt(a, '1', 'dafs', 'candy') ); // prop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment