diff --git a/solutions/javascript/convert-array.js b/solutions/javascript/convert-array.js new file mode 100644 index 0000000..5fda35b --- /dev/null +++ b/solutions/javascript/convert-array.js @@ -0,0 +1,26 @@ +'use strict'; + +function getSwapIndex(currentInd, n) { + var swapInd = (currentInd % 3) * n + parseInt(currentInd/3); + while (swapInd < currentInd) { + swapInd = getSwapIndex(swapInd, n); + } + + return swapInd; +} + +function convert(arr) { + var n = parseInt(arr.length / 3); + + for(var i = 0; i < arr.length; i++) { + var swapInd = getSwapIndex(i, n); + + var tmp = arr[i]; + arr[i] = arr[swapInd]; + arr[swapInd] = tmp; + } + + return arr; +} + +module.exports = convert; diff --git a/tests/javascript/convert-array.js b/tests/javascript/convert-array.js new file mode 100644 index 0000000..0056872 --- /dev/null +++ b/tests/javascript/convert-array.js @@ -0,0 +1,26 @@ +var assert = require('assert'); +var convert = require('../../solutions/javascript/convert-array'); + +describe('Convert Array', function() { + it('should convert an array', function() { + var arr = [ + 'a1', 'a2', 'a3', 'a4', 'a5', + 'b1', 'b2', 'b3', 'b4', 'b5', + 'c1', 'c2', 'c3', 'c4', 'c5' + ]; + + var expectedArr = [ + 'a1', 'b1', 'c1', + 'a2', 'b2', 'c2', + 'a3', 'b3', 'c3', + 'a4', 'b4', 'c4', + 'a5', 'b5', 'c5' + ]; + + convert(arr); + + for(var i = 0; i < arr.length; i++) { + assert.equal(arr[i], expectedArr[i]); + } + }) +})