I'm doing some exercises on JavaScript and I came into a question that asks to rotate arrays item to the left with a given n rotation steps. The exercises are tested with Jasmine. Tried several method but none are meeting the precondition:
it("Arrays: Rotation Gauche", function () {
// DESCRIPTION:
// A left rotation operation on an array shifts each element
// from the array to the left. For example, if left rotations are
// done on the array [1,2,3,4,6], the array would become [3,4,5,1,2]
//
// Given an array of integers a, do n left rotations on
// the array. The function returns the updated array.
function rotateLeft(a, n) {
// TODO: implement the function as described in DESCRIPTION
let len = 0,j=0
var b =[]
len = a.length
for (let i = n; i < len; i++){
b[j] = a[i]
j++
}
for (let i = 0; i < n; i++){
b[j] = a[i]
j++
}
return b;
}
// Jasmin unit tests
let input = [1, 2, 3, 4, 6];
let expected = [3, 4, 5, 1, 2];
expect(rotateLeft(input, 4)).toBe(expected);
input = [41, 73,89,7,10,1,59,58,84,77,77,97,58,1,86,58,26,10,86,51];
expected = [7,97, 58, 1, 86, 58, 26, 10, 86, 51, 41, 73, 89, 7, 10, 1, 59, 58, 84, 77]
expect(rotateLeft(input, 10)).toBe(expected);
input = [98,67,35,1,74,79,7,26,54,63,24,17,32,81];
expected = [26, 54, 63, 24, 17, 32, 81, 98, 67, 35 ,1 ,74, 79, 7]
expect(rotateLeft(input, 7)).toBe(expected);
});
My last attempt is below the TODO comment.
And obviously the tests aren't passing. I tried several approaches without success. It's just an exercise, so I would like some guidance.
Thanks