Write a function to rotate a two-dimensional array 90 degrees clockwise, and name it rotateArray
. The array is always a perfect rectangle.
const rotateArray = m => m[0].map((_,i)=>m.map(r=>r[i]).reverse());
// todo: make it work for empty arrays
const chai = require("chai");
const assert = chai.assert;
describe("Array Rotator", () => {
it("should rotate the array, i guess", () => {
assert.strictEqual(JSON.stringify(rotateArray([
[1,2],
[3,4]
])),JSON.stringify([
[3,1],
[4,2]
]));
assert.strictEqual(JSON.stringify(rotateArray([
[1,2,3],
[4,5,6]
])),JSON.stringify([
[4,1],
[5,2],
[6,3]
]));
assert.strictEqual(JSON.stringify(rotateArray([
[1,2],
[3,4],
[5,6]
])),JSON.stringify([
[5,3,1],
[6,4,2]
]));
});
});
Come up with a creative way to replicate the functionality of Math.sign()
(extra credits for not using the Math
module at all).
The function should be named numberSign
, and it should return +1 for positive numbers, -1 for negative, and 0 for 0.
const numberSign = x => x/Math.abs(x) || 0;
const chai = require("chai");
const assert = chai.assert;
describe("Solution", () => {
it("should return 0 as is", () => {
assert.strictEqual(numberSign(0), 0);
assert.strictEqual(numberSign(-0), 0);
});
it("should return -1 for negative numbers", () => {
assert.strictEqual(numberSign(-4), -1);
assert.strictEqual(numberSign(-8), -1);
assert.strictEqual(numberSign(-82), -1);
assert.strictEqual(numberSign(-267), -1);
});
it("should return 1 for positive numbers", () => {
assert.strictEqual(numberSign(2), 1);
assert.strictEqual(numberSign(9), 1);
assert.strictEqual(numberSign(63), 1);
assert.strictEqual(numberSign(983), 1);
});
});