Chunk / Chop
Implement a function that creates an array of elements split into smaller groups of a specified size.
function ChunkOrChop(array, limit) {
let results = [];
let i = 0;
while (i < array.length) {
results.push(array.slice(i, i + limit));
i = i + limit;
}
return results;
}
console.log(ChunkOrChop([1, 2, 3, 4, 5, 6], 2));
// [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
console.log(ChunkOrChop([1, 2, 3, 4, 5], 2));
// [ [ 1, 2 ], [ 3, 4 ], [ 5] ]
Clamp
Implement a function to clamp a number within the inclusive lower and upper bounds.
function clampNumber(num, minValue, maxValue) {
return Math.min(Math.max(minValue, num), maxValue);
}
const value = 15;
const lowerBound = 5;
const upperBound = 10;
const clampedValue = clampNumber(value, lowerBound, upperBound);
console.log(clampedValue); // 10
Deep Clone
Implement a function that performs a deep copy of a value.
function deepClone(value) {
if (typeof value !== "object" || value === null) {
return value;
}
if (Array.isArray(value)) {
return value.map((num) => deepClone(num));
}
return JSON.parse(JSON.stringify(value));
}
function runTests() {
// Test case 1: Simple object
const originalObject = { a: 1, b: "hello", c: true };
const clonedObject = deepClone(originalObject);
console.log("Test 1:", originalObject === clonedObject);
// Test case 2: Nested object
const nestedObject = { a: 1, b: { c: 2, d: [3, 4] } };
const clonedNestedObject = deepClone(nestedObject);
console.log("Test 2:", nestedObject === clonedNestedObject);
// Test case 3: Array
const originalArray = [1, "two", { three: 3 }];
const clonedArray = deepClone(originalArray);
console.log("Test 3:", originalArray === clonedArray);
// Test case 4: Nested array
const nestedArray = [1, [2, 3], { four: [5, 6] }];
const clonedNestedArray = deepClone(nestedArray);
console.log("Test 4:", nestedArray === clonedNestedArray);
// Test case 5: Primitive value
const primitiveValue = 42;
const clonedPrimitiveValue = deepClone(primitiveValue);
console.log("Test 5:", primitiveValue === clonedPrimitiveValue);
}
runTests();
// Test 1: false
// Test 2: false
// Test 3: false
// Test 4: false
// Test 5: true