What is the best way to shift a multidimensional array in Javascript? -
i'm trying create javascript function shifts array right x units y units. must keep array size same, , must call unloadchunk elements getting shifted off multidimensional array. here current implementation:
function shift(x, y) { if (x > 0) { (var = 0; < chunks.length; i++) { (var j = chunks[i].length - 1; j >= 0; j--) { if(j + x > chunks[i].length - 1 && chunks[i][j]) { unloadchunk(i, j); } if (j < x) { chunks[i][j] = null; } else { chunks[i][j] = chunks[i][j - x]; } } } } else if (x < 0) { (var = 0; < chunks.length; i++) { (var j = 0; j < chunks[i].length; j++) { if(j + x < 0 && chunks[i][j]) { unloadchunk(i, j); } if (j - x >= chunks[i].length) { chunks[i][j] = null; } else { chunks[i][j] = chunks[i][j - x]; } } } } if (y > 0) { (var = 0; < chunks.length; i++) { if (i + y >= chunks.length) { (var j = 0; j < chunks.length; j++) { if(i - y < 0 && chunks[i][j]) { unloadchunk(i, j); } chunks[i][j] = null; } } else { (var j = 0; j < chunks.length; j++) { if(i - y < 0 && chunks[i][j]) { unloadchunk(i, j); } chunks[i][j] = chunks[i + y][j]; } } } } else if (y < 0) { (var = chunks.length - 1; >= 0; i--) { if (i + y < 0) { (var j = 0; j < chunks.length; j++) { if(i - y > chunks.length - 1 && chunks[i][j]) { unloadchunk(i, j); } chunks[i][j] = null; } } else { (var j = 0; j < chunks.length; j++) { if(i - y > chunks.length - 1 && chunks[i][j]) { unloadchunk(i, j); } chunks[i][j] = chunks[i + y][j]; } } } } }
if you're having trouble understanding want shift function do, take @ this fiddle , @ html output. attempt @ creating shift function works, has 10 loops. question was, there more efficient, less verbose way this?
this proposal uses
array#foreach
: visit each itemarray#map
: return value each itemarray#pop
: removes , return last elementarray#push
: adds 1 or more elements @ endarray#shift
: removes , return first elementarray#unshift
: adds 1 or more elements @ beginning
for better visibillity, replaced null
value 1000
, 2000
, 3000
, 4000
.
function shift(x, y) { while (x > 0) { chunks.foreach(function (a) { a.pop(); a.unshift(1000); }); x--; } while (x < 0) { chunks.foreach(function (a) { a.shift(); a.push(2000); }); x++; } while (y > 0) { chunks.unshift(chunks.pop().map(function () { return 3000; })); y--; } while (y < 0) { chunks.push(chunks.shift().map(function () { return 4000; })); y++; } } function print(msg) { document.body.innerhtml += '<p>' + msg + '</p>'; } function printarr(arr) { (var = 0; < arr.length; i++) { print(json.stringify(arr[i])) } } var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]]; print("chunks: " + json.stringify(chunks)); shift(1, 0); print("shifting right 1. chunks: "); printarr(chunks); shift(-1, 0); print("shifting left 1. chunks: "); printarr(chunks); shift(0, 1); print("shifting 1. chunks: "); printarr(chunks); shift(0, -1); print("shifting down 1. chunks: "); printarr(chunks);
Comments
Post a Comment