Created
June 18, 2015 22:53
-
-
Save rewonc/fee8174208d8d53e7028 to your computer and use it in GitHub Desktop.
Snail -- reverse array
This file contains hidden or 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
// Return an array sorted in a "snail" format -- that is, around the edge and then the middle. | |
// var arr = [[1,2,3], | |
// [4,5,6], | |
// [7,8,9]]; | |
// var arr1 = [[1]]; | |
// var arr2 = [[1, 2], [3, 4]]; | |
// Test.assertSimilar(snail(arr1), [1]); | |
// Test.assertSimilar(snail(arr), [1,2,3,6,9,8,7,4,5]); | |
var snail = function(array) { | |
res = []; | |
return res.concat(top(array), right(array), bottom(array), left(array), inside(array)); | |
} | |
function top(array){ | |
if (array.length < 2) { | |
return array[0]; | |
} | |
return array[0]; | |
} | |
function right(array){ | |
if (array.length < 2) { | |
return []; | |
} | |
var res = []; | |
for (var i = 1; i<array.length - 1; i++){ | |
res.push(array[i][array.length - 1]); | |
} | |
return res; | |
} | |
function bottom(array){ | |
if (array.length < 2) { | |
return []; | |
} | |
return array[array.length - 1].reverse(); | |
} | |
function left(array){ | |
if (array.length < 2) { | |
return []; | |
} | |
var res = []; | |
for (var i = array.length - 2; i > 0; i--){ | |
res.push(array[i][0]); | |
} | |
return res; | |
} | |
function inside(array){ | |
if (array.length < 3) { | |
return []; | |
} | |
var res = []; | |
for (var i = 1; i<array.length - 1; i++){ | |
res.push(array[i].slice(1, array[i].length - 1)); | |
} | |
return snail(res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment