Skip to content

Instantly share code, notes, and snippets.

@kaustavha
Created October 8, 2019 02:05
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 kaustavha/500a6e3a856b243e26b21afe5c5777e7 to your computer and use it in GitHub Desktop.
Save kaustavha/500a6e3a856b243e26b21afe5c5777e7 to your computer and use it in GitHub Desktop.
Javascript - turn array with negative indices to normal array
/**
* Returns a normal iterable array from an array with -ve numbers, padding any missing elements with the provided filler
* Use case - algo problems where we move in 2d space to -ve numbered places in an arr or matrix
* @param {Array} obj An array containing -ve numbers as indices, behaves like an object at times
* @param {*} filler Filler material to populate missing members e.g. array or string
* @param {Number} maxPos maximum positive value of a key in array
* @param {Number} maxNeg max -ve value of a key in the incoming array
* @returns {Array} Sorted array
*/
function _objToArr(obj, filler, maxPos, maxNeg) {
// js arr with -ev nums are treated similiar to obj
// -ve keys come after +ve numeric keys
// +ve keys are stored in asc order
// -ve keys are stored in desc order
// i.e. 0 1 2 -1 -2
// we also need to manually iter keys since .forEach on arr ignores -ve keys
// herein we create a left array for the -ve keys
// right arr for +ve keys
// fill and pad them to the max lengths then return concated result
// using filler value for missing members
let outArrLeft = new Array();
let outArrRight = new Array(maxPos);
for (let i=0; i<=maxPos; i++) {
// fill right arr w/ +ve nums
if (obj[i] == undefined && outArrRight[i] == undefined) {
outArrRight[i] = filler;
} else {
outArrRight[i] = obj[i];
}
}
for (let i=-1; i>=maxNeg; i--) {
// fill left arr w/ -ve nums
if (obj[i] == undefined && outArrLeft[i] == undefined) {
outArrLeft.unshift(filler);
} else {
outArrLeft.unshift(obj[i]);
}
}
return outArrLeft.concat(outArrRight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment