How to reduce the number of if - javascript

Is there a way to reduce the number of "if" in this code?
function test(input) {
if ((input % 3 == 0) && (input % 5 == 0)) {
return 'fizzbuzz';
} else if (input % 3 == 0) {
return 'fizz';
} else if (input % 5 == 0) {
return 'buzz';
} else {
return '' + input;
}
}
for (var i = 1; i < 100; i++) {
console.log(test(i));
}

You can avoid that by storing the comparison values:
var mod3 = input % 3 == 0;
var mod5 = input % 5 == 0;
... creating a lookup table ...
var outs = [input, "fizz", "buzz", "fizzbuzz"];
... and indexing it ...
return outs[(+mod3) + 2 * (+mod5)];
... no ifs!

You can use the ternary operator:
return ((input%3==0)&&(input%5==0)) ? 'fizz buzz'
: (input%3==0) ? 'fizz'
: (input%5==0) ? 'buzz'
: '' + input;

If you don't want to use if's why not try case syntax?
http://www.w3schools.com/js/js_switch.asp
Alternatively use the JS shorthand for if
so that:
var something;
if (2 + 2 === 4){
something = "Yup!"
} else {
something = "Nope"
}
becomes
var something = 2 + 2 === 4 ? "Yup!" : "Nope";

You can get rid of the first "if" altogether, because 3 and 5 and "fizz" and "buzz" are used in the later ones. You can also wait to return until the end. Something like:
var str = "";
if (input % 3 === 0){
str +="fizz";
}
if (input % 5 === 0 ){
str +="buzz";
} else {
str = input;
}
return str;

Related

How do i return the result of all loops in javascript?

I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));

How to convert lowercase uppercase?(with if conditions on different digits.)

Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}

Is there a way to overwrite an array when I push a new value to it?

Maybe I am doing this wrong but I'm trying to update my arrays so that they just have the most current thing submitted in them. Is there a way to do this? I can't seem to think of anything and push just adds more to the array each time.
$( document ).ready(function() {
var divisTwo = [];
var divisThree = [];
function getNumbers(nums){
// iterates through these to determine if fiz, buzz or fizzbuzz.
if(nums % 105 === 0){
return 'Fizz Buzz Pop'
} else if (nums % 35 === 0){
return 'Buzz Pop'
} else if (nums % 21 === 0){
return 'Fizz Pop'
} else if (nums % 15 === 0){
return 'Fizz Buzz'
} else if (nums % 7 === 0){
return 'Pop'
} else if(nums % 5 === 0 ){
return 'Buzz'
} else if(nums % 3 === 0){
return divisThree || 'Fizz'
} else if (nums % 2 === 0){
return divisTwo
} else {
return nums
}
};
$('#click').click(function(){
// Gets value from input box.
var inputValue = document.getElementById("fizz-input").value;
// appends text to an h2 in the html
$("#fizz-buzz-output").text(getNumbers(inputValue));
});
$('#change-names').click(function test(name){
var multiTwo = document.getElementById("multiples-of-two").value;
var multiThree = document.getElementById("multiples-of-three").value;
divisTwo.push(multiTwo);
divisThree.push(multiThree);
console.log(divisTwo);
console.log(divisThree);
});
});
Use simple variables instead of arrays.
$( document ).ready(function() {
var divisTwo;
var divisThree;
function getNumbers(nums){
// iterates through these to determine if fiz, buzz or fizzbuzz.
if(nums % 105 === 0){
return 'Fizz Buzz Pop'
} else if (nums % 35 === 0){
return 'Buzz Pop'
} else if (nums % 21 === 0){
return 'Fizz Pop'
} else if (nums % 15 === 0){
return 'Fizz Buzz'
} else if (nums % 7 === 0){
return 'Pop'
} else if(nums % 5 === 0 ){
return 'Buzz'
} else if(nums % 3 === 0){
return divisThree || 'Fizz'
} else if (nums % 2 === 0){
return divisTwo
} else {
return nums
}
};
$('#click').click(function(){
// Gets value from input box.
var inputValue = document.getElementById("fizz-input").value;
// appends text to an h2 in the html
$("#fizz-buzz-output").text(getNumbers(inputValue));
});
$('#change-names').click(function test(name){
divisTwo = document.getElementById("multiples-of-two").value;
divisThree = document.getElementById("multiples-of-three").value;
console.log(divisTwo);
console.log(divisThree);
});
});
You must equate your variable of array to empty inside the function, so that every fire of the click event, it is empty. Also don't use pop, because it only removes last element.
var divisTwo = [];
var divisThree = [];
$('#change-names').click(function(){
divisTwo = [];
divisThree = [];
var multiTwo = document.getElementById("multiples-of-two").value;
var multiThree = document.getElementById("multiples-of-three").value;
divisTwo.push(multiTwo);
divisThree.push(multiThree);
console.log(divisTwo);
console.log(divisThree);
});

Undefined result from Fizz Buzz game Javascript

I'm having an assignment where I have to do the FizzBuzz game in Javascript. The problem is I get 'Answer = undefined' when I run the function. I have to print it with a comma separated value but I think I can figure that out for my self though; Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write("Fizz Buzz");
}else if(i % 3 == 0) {
document.write("Fizz");
}else if(i % 5 == 0) {
document.write("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));
Because the fizzBuzz function isn't returning anything. You need to return a result from that function. document.write writes out text to the document.
You aren't returning anything from your function.
ANSWER will be what you 'return' in a function.
If you wanted to return all the values you would need to do somthing like
var ans='';
...
if ( whatever) ans+= 'Fizz Buzz,';
....
return ans.substring(0,ans.length-1);
Some modifications to your code...
function fizzBuzz(start, stop) {
var i;
var results = [];
for (i = start; i <= stop; i++) {
if (i % 15 == 0) {
results.push('Fizz Buzz');
} else if (i % 3 == 0) {
results.push('Fizz');
} else if (i % 5 == 0) {
results.push('Buzz');
} else {
// cast to string just so all the results in the array are string
results.push(i + '');
}
}
return results;
}
ANSWER = fizzBuzz(4, 22); // output: [ '4', 'Fizz', 'Buzz', '7', '8', ...etc ]
<html>
<script>
function fizzBuzz(start, stop) {
var str = 'ANSWER = ';
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
str += "Fizz Buzz";
}else if(i % 3 == 0) {
str += "Fizz";
}else if(i % 5 == 0) {
str += "Buzz";
}else {
str += i;
}
if (i<stop)
str += ", ";
}
document.getElementById('writeto').innerHTML += str;
}
fizzBuzz(4, 22);
</script>
<body>
<a id='writeto'></a>
</body>
</html>

Javascript Fizzbuzz Issue

I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

Categories

Resources