In: Computer Science
I have a countdown sequence i have to do for a code, when the result is entered it starts to countdown, i tried imputting some codes but i am clueless ( javascript):
/*******************************************************************************
* Problem 3: create count-down number sequence strings
*
* A count-down sequence is a String made up of a descending list of numbers.
* For example, the count-down sequence for the number 3 would be:
*
* "321"
*
* Write the countDownSequence function below, allowing any number between
* 1 and 10 to be accepted. Otherwise, throw an error (see
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
*
* If we called countDownSequence(5) we'd expect to get:
*
* "54321"
*
* If we called countDownSequence(55) we'd expect to have an error thrown
*
* Error: only start values between 1 and 10 are valid
*
* @param {Number} start - the number to start counting down from (must be 10 or smaller).
******************************************************************************/
function countDownSequence(start) {
var ret = '';
while (start >= 0) {
ret += start;
if (start > 0) {
ret += '';
}
start--;
}
return ret;
// Your code here...
}
It has to pass these tests:
const { countDownSequence } = require('./solutions');
describe('Problem 3 - countDownSequence() function', function() {
test('proper count down sequence from 10', function() {
let start = 10;
let result = countDownSequence(start);
expect(result).toBe('10987654321');
});
test('proper count down sequence from 1', function() {
let start = 1;
let result = countDownSequence(start);
expect(result).toBe('1');
});
test('starting at 0 should throw', function() {
function shouldThrow() {
// Using 0 is invalid, this should throw
countDownSequence(0);
}
expect(shouldThrow).toThrow();
});
test('starting at a negative number should throw', function() {
function shouldThrow() {
// Using -100 is invalid, this should throw
countDownSequence(-100);
}
expect(shouldThrow).toThrow();
});
test('starting at a number greater than 10 should throw', function() {
function shouldThrow() {
// Using 11 is invalid, this should throw
countDownSequence(11);
}
expect(shouldThrow).toThrow();
});
});
Try replacing the code of the function "countDownSequence()" with the below code and the code is as follows:
function countDownSequence(start) {
var ret = '';
try {
if (start >= 0 && start <= 10) {
while(start >=0 ){
ret += start;
start--;
}
return ret;
}
else {
throw "Error: only start values between 1 and 10 are valid";
}
}catch(err){
console.log(err)
}
}
This implementation of the countDownSequence should pass the test cases stated in the question.
I am attaching the output sample, I am just running the html file which contain the above code and calling the countDownSequence function with different parameter
If you face any problem let me know in the comment section. I will try to solve it.