scrimba
Note at 1:13
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Note at 1:13
AboutCommentsNotes
Note at 1:13
Expand for more info
main.js
run
preview
console
/** Throws if 
* @param number[]
* @returns number[]
*/

function arrayPreviousLess(nums) {
if(!Array.isArray(nums)){
throw new Error("Invalid input");
}
const { length } = nums;
const arrayClone = [...nums];
outerLoop: for (let i = 0; i < length; i += 1) {
if(typeof nums[i] !== 'number'){
throw new Error('Invalid input');
}
for (let j = i - 1; j >= 0; j -= 1) {
if (nums[i] > nums[j]) {
arrayClone[i] = nums[j];
continue outerLoop;
}
}
arrayClone[i] = -1;
}
return arrayClone;
}

/* SOLUTION 2
function arrayPreviousLess(nums) {
if(!Array.isArray(nums)){
throw new Error("Invalid input");
}
const arrayClone = [...nums];
nums.forEach((element, index) => {
if(typeof element !== 'number'){
throw new Error('Invalid input');
}
for(let i = index - 1; i >= 0; i--){
if(element > nums[i]){
arrayClone[index] = nums[i];
return;
}
}
arrayClone[index] = -1;
})
return arrayClone;
}

*/
/**
* Test Suite
*/
describe('arrayPreviousLess()', () => {
it('expects arrayPreviousLess to be a function', () => {
expect(typeof arrayPreviousLess === "function").toBe(true);
});
it('expects arrayPreviousLess([3, 5, 2, 4, 5]) to return [-1, 3, -1, 2, 4]', () => {
expect(arrayPreviousLess([3, 5, 2, 4, 5])).toEqual([-1, 3, -1, 2, 4]);
});
it('expects arrayPreviousLess([]) to return []', () => {
expect(arrayPreviousLess([])).toEqual([]);
});
it('expects arrayPreviousLess([2, 2, 2]) to return [-1, -1, -1]', () => {
expect(arrayPreviousLess([2, 2, 2])).toEqual([-1, -1, -1]);
});
it('expects arrayPreviousLess([1, 2, 3, 10]) to return [-1, 1, 2, 3]', () => {
expect(arrayPreviousLess([1, 2, 3, 10])).toEqual([-1, 1, 2, 3]);
});
it('expects arrayPreviousLess([5, 3, 2]) to return [-1, -1, -1]', () => {
expect(arrayPreviousLess([5, 3, 2])).toEqual([-1, -1, -1]);
});
it('expects arrayPreviousLess([5, 3, "2"]) to throw an error', () => {
expect(() => arrayPreviousLess([5, 3, '2'])).toThrow(new Error('Invalid input'));
});
it('expects arrayPreviousLess([0]) to return [-1]', () => {
expect(arrayPreviousLess([0])).toEqual([-1]);
});
it('expects arrayPreviousLess(false) to throw an error', () => {
expect(() => arrayPreviousLess(false)).toThrow(new Error('Invalid input'));
});

});
Console
/index.html
LIVE