I am doing this assignment:
Write a function named snapCrackle that takes one parameter: maxValue. This function should loop through 1 up to maxValue (inclusive) and build a string with the following conditions: If a number is odd, concatenate "Snap, " to the end of the string. If a number is a multiple of 5, concatenate "Crackle, " to the end of the string. If a number is both odd and a multiple of 5 concatenate "SnapCrackle, " to the end of the string. If a number is neither odd or a multiple of 5, concatenate the number and ", " to the end of the string. This function should console.log() the final string after maxValue iterations of the loop.
This is my solution:
let c = "Snap, ";
let i = "Crackle, ";
let x = "SnapCrackle, ";
let b = ",";
let maxValue = 20;
let counter = 1;
let output = "";
let list = ["snap", "crackle", "snapCrackle"];
function snapCrackle() {
while (counter <= maxValue) {
if (counter % 5 === 0 && counter % 2 !== 0) {
console.log(x + counter);
} else if (counter % 5 === 0) {
console.log(i + counter);
} else if (counter % 5 === 0 || counter % 2 !== 1) {
console.log(counter + b);
} else if (counter % 2 !== 0) {
console.log(c + counter);
}
counter++;
}
}
console.log();
return snapCrackle();
let results = " ";
console.log(snapCrackle());
I was told:
Great start! You have everything you need, but it should be a single string. For Snap, Crackle, and SnapCrackle, you shouldn't display the number next to it, although I appreciate the cleverness and effort of it. A hint I will give for solving this is creating an empty string and concatenating the results to it!
How do I push my counter to an array so I can console.log
a single line, or how can I make the function itself output a single line?
You have done all the hard-work. Small changes and you are good with your answer.
let c = "Snap";
let i = "Crackle";
let x = "SnapCrackle";
let maxValue = 20;
let counter = 1;
// let output = ""; // not required rather use an array
// let list = ["snap", "crackle", "snapCrackle"]; // not required
let outPutArr = [];
function snapCrackle() {
while (counter <= maxValue) {
if (counter % 5 === 0 && counter % 2 !== 0) {
outPutArr.push(x);
} else if (counter % 5 === 0) {
outPutArr.push(i);
} else if (counter % 5 === 0 || counter % 2 !== 1) {
outPutArr.push(counter);
} else if (counter % 2 !== 0) {
outPutArr.push(c);
}
counter++;
}
return outPutArr // return the created array from conditions
}
console.log(snapCrackle().join()); // Return the join of the array