How could I make this code more effective - js? - javascript

function checkValue(val) {
if (val === 1 || val === 4 || val === 7) {
return val - 2
}
if (val === 2 || val === 5 || val === 8) {
return val - 1
}
if (val === 3 || val === 6 || val === 9) {
return val
}
}
console.log(6 - checkValue(6))
how to make this code simple and dynamic to prevent repetitive code writing

function checkValue(val){
const reminder = val % 3;
return reminder ? val - (3 - reminder) : val;
}

Related

How to check null and implement logic based on that in JS?

I have parseNotAvailable function that based on version have some logic, so i have penalties that has coming as version 2 but i need to have logic same as version 1, So i tried to pass as null to get 0 but its not working and throwing error.
Any better approach to achieve above task ?
main.js
let newPrice = {
copayEmployer: parseNotAvailable('N/A', 1),
penalties: parseNotAvailable('N/A', null),
secondaryClaimNumber: parseNotAvailable('N/A',2)
};
function parseNotAvailable(value, version) {
if ((value === 'N/A' || value === 'n/a') && (version || version === 1)) {
return 0;
} else if ((value === 'N/A' || value === 'n/a') && version === 2) {
return null;
} else {
return parseFloat(value);
}
};
// console.log(parseNotAvailable('N/A', 1));
console.log(newPrice);
expected Result
{ copayEmployer: 0, penalties: 0, secondaryClaimNumber: null }
with above code its returning
{ copayEmployer: 0, penalties: NaN, secondaryClaimNumber: 0 }
In parseNotAvailable('N/A', null) version is null and does not pass if statements na goes to else statement return parseFloat(value);
In parseNotAvailable('N/A', 2) version is 2 and it pass first if statements... ||(value || value === 1) and return 0;
You have wrong assertion if ((value === 'N/A' || value === 'n/a') && (version || version === 1)) it should be if ((value === 'N/A' || value === 'n/a') && (!version || version === 1))
You're code is flowing to the else block and trying attempting to parseInt('N/A'), which obviously is NaN. You may want to rethink your conditions there. I added a simple isNaN check to your code as you can see:
try {
let newPrice = {
copayEmployer: parseNotAvailable('N/A', 1),
penalties: parseNotAvailable('N/A', null),
secondaryClaimNumber: parseNotAvailable('N/A', 2)
};
console.log(newPrice);
} catch (err) {
console.error(err)
}
function parseNotAvailable(value, version) {
if ((value === 'N/A' || value === 'n/a') && (version || version === 1)) {
return 0;
} else if ((value === 'N/A' || value === 'n/a') && version === 2) {
return null;
} else {
//Do a check here for NaN value - this probably isnt needed if you straigten out your flow control conditions
if (isNaN(value)) {
throw `${value} is NaN`;
}
return parseFloat(value);
}
};

Simple modulo tester

I have a simple, modulo based script, which runs for 3 and 6 digits to else. There are also cases for these numbers, which condition should fit also to these numbers.
function caffeineBuzz(n){
var returnvalue;
if (n % 3 == 0)
returnvalue = "Java";
if (n % 3 == 0 && n % 4 == 0)
returnvalue = "Coffee";
if (n % 3 == 0 && n % 2 == 0)
returnvalue = "Java" + "Script"
if (n % 4 == 0 && n % 2 == 0)
returnvalue = "Coffee" + "Script"
else
returnvalue = "mocha_missing!"
return returnvalue;
}
n stands for input, that is an integer and returnvalue should be a string.
Update:
Most specific -> less specific approach helped me, but there are cases, when it returns with wrong value.
function caffeineBuzz(n){
var returnvalue;
if (n % 4 == 0)
returnvalue = "Coffee" + "Script"
else if (n % 3 == 0 && n % 4 == 0)
returnvalue = "Coffee";
else if (n % 3 == 0 && n % 2 == 0)
returnvalue = "Java" + "Script"
else if (n % 3 == 0)
returnvalue = "Java";
else
returnvalue = "mocha_missing!"
return returnvalue;
}
This function is the guesstimation of the answer based on comments.
function caffeineBuzz(n){
//Storing n's modulos to not calculate them multiple times
var mod3 = (n % 3 == 0)
var mod4 = (n % 4 == 0);
var mod2 = mod4 || (n % 2 == 0);
//Maybe: return (mod3 ? ("Java" + (mod4 ? "Coffee" : "")) + (mod2 ? "Script" : "") : "mocha_missing!");
return (mod3 ? ((mod4 ? "Coffee" : "Java") + (mod2 ? "Script" : "")) : ("mocha_missing!"));
}

Simple PIN validation

Task:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.
My solution:
function validatePIN (pin) {
//return true or false
if (!isNaN(pin) && Number.isInteger(pin) && pin.toString().length == 4 || pin.toString().length == 6) {
return true
} else {
return false
}
}
The only bug I get is when I pass 4 digits as a string ("1234") - it equals false.
function validatePIN (pin) {
return typeof pin === 'string' && // verify that the pin is a string
Number.isInteger(+pin) && // make sure that the string is an integer when converted into a number
[4, 6].includes(pin.length) // only accepts 4 and 6 character pins
}
function validatePIN(pin) {
var isNumber = /^\d+$/.test(pin) && (pin.length == 4 || pin.length == 6)
return isNumber
}
validatePIN('0193')
//returns true
You can use Array.prototype.every(), Array.prototype.some(), String.prototype.match()
<input type="text" />
<button>validate pin</button>
<script>
var validatePIN = (args) => {[...args] = args;
return args.every(v => v.match(/\d/)) &&
[4, 6].some(n => args.length === n)};
document.querySelector("button")
.addEventListener("click", (e) =>
alert(validatePIN(e.target.previousElementSibling.value))
)
</script>
function validatePIN (pin) {
//return true or false
return /^\d+$/.test(pin) && (pin.length === 4 || pin.length === 6)
}
function validatePIN (pin) {
if (pin.length !== 4 && pin.length !== 6) {
return false;
}
for (let i = 0; i < pin.length; i++) {
if (pin[i] > '9' || pin[i] < '0') {
return false;
}
}
return true;
}
Here is another way to solve using regular expression.
function validatePIN(pin) {
return /^(\d{4}|\d{6})$/.test(pin)
}
validatePIN('2345')
//returns true
validatePIN('2.45')
//reutrns false
function validatePIN (pin) {
if (pin.length == 4 || pin.length == 6)
{
for (let i = 0; i < pin.length; i++)
{
if (pin[i] == "0" ||
pin[i] == "1" ||
pin[i] == "2" ||
pin[i] == "3" ||
pin[i] == "4" ||
pin[i] == "5" ||
pin[i] == "6" ||
pin[i] == "7" ||
pin[i] == "8" ||
pin[i] == "9") ;
else return false;
}
return true;
}
else return false;
}
this code checks the PIN-length and passes all test tasks with numbers and not numbers...
public static boolean validatePin(String pin) {
return pin.matches("\\d{4}|\\d{6}");
}

How to reduce the number of if

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;

Javascript if/if else/else not working

So I have this javascript, but it's not working.
var verbs = [ ["ambulo", "ambulare", "ambulavi", "ambulatus"], ["impedio", "impedire", "impedivi", "impeditus"] ]
var verbNumber = verbs.length - 1;
function randomIntFromInterval(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
/* Picks a verb */
var thisVerb = verbs[randomIntFromInterval(0, verbNumber)];
/* Checks the conjugation */
var second = thisVerb[1];
var secondLength = second.length;
var start = secondLength - 3;
var secondEnding = second.substring(start, secondLength);
var conjugationNumber = 0;
if (secondEnding === "are") {
conjugationNumber = 1;
} else if (secondEnding === "ēre") {
conjugationNumber = 2;
} else if (secondEnding === "ere") {
conjugationNumber = 3;
} else if (secondEnding === "ire") {
conjugationNumber = 4;
} else {
console.log("error");
};
/* Randomly picks how to conjugate */
var tense = randomIntFromInterval(1, 6);
var person = randomIntFromInterval(1, 3);
var number = randomIntFromInterval(1, 2);
var voice = randomIntFromInterval(1, 2);
/* Conjugates */
var thisDictEntry = 0;
if ((conjugationNumber === 1 || 2) && (tense === 1 || 2 || 3)) {
thisDictEntry = 2;
} else if ((conjugationNumber === 3 || 4) && (tense === 1 || 2 || 3)) {
thisDictEntry = 1;
} else if ((tense === 4 || 5 || 6) && (voice === 1)) {
thisDictEntry = 3;
} else if ((conjugationNumber === 3 || 4) && (voice === 2)) {
thisDictEntry = 4;
} else {
console.log("Error");
};
What should happen is a random verb (array within an array) is picked, then becomes randomly conjugated. All the code works up until the if/else if/else statements under the /* Conjugates */. That, for some reason, always sets thisDictEntry to 2.
Why?
The first condition:
((conjugationNumber === 1 || 2) && (tense === 1 || 2 || 3))
should be:
((conjugationNumber === 1 || conjugationNumber === 2) && (tense === 1 || tense === 2 || tense === 3))
the problem with your version is that javascript does the following:
conjugationNumber === 1 // this results in true/false
or
2 // this is always true
because js evaluates it as truthy.

Categories

Resources