challenge ctci-array-left-rotation

This commit is contained in:
Lorenzo Iovino 2024-01-24 18:55:09 +01:00
parent 069cfb45fe
commit 3b7d0b4574
3 changed files with 34 additions and 1 deletions

3
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules node_modules
build build
.idea .idea
.DS_STORE

View file

@ -0,0 +1,17 @@
import {describe, it} from "node:test";
import assert = require("node:assert");
import {rotLeft} from "./ctci-array-left-rotation";
describe("Ctci Array Left Rotation", () => {
describe("rotLeft", () => {
it("an empty array return itself ", () => {
assert.deepStrictEqual(rotLeft([], 100), [])
assert.deepStrictEqual(rotLeft([], 1), [])
assert.deepStrictEqual(rotLeft([], 0), [])
})
it("rotate an array of X position should return the array rotated left by X position", () => {
assert.deepStrictEqual(rotLeft([1, 2, 3, 4, 5], 4), [5, 1, 2, 3, 4]);
})
});
})

View file

@ -0,0 +1,15 @@
export function rotLeft(a: Array<number>, d: number): Array<number> {
if(a.length === 0) {
return [];
}
if(a.length == d) {
return a.reverse();
}
const firstElements = a.slice(0, d)
a.splice(0, d);
a = a.concat(firstElements);
return a;
}