Simplified javascript some function with almost the same code - javascript

Hei, I'm working an app to simulate prices. I have a code like this.
function max110(x) {
if (x >= '1' && x <= '50') {
var sum = 120 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else if (x >= '51' && x <= '100') {
var sum = 115 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else if (x >= '101' && x <= '200') {
var sum = 110 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else {
hasil.value = 'error!';
}
}
function max115(x) {
if (x >= '1' && x <= '50') {
var sum = 125 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else if (x >= '51' && x <= '100') {
var sum = 120 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else if (x >= '101' && x <= '200') {
var sum = 115 * x;
hasil.value = 'Rp.' + parseFloat(sum * 1000);
} else {
hasil.value = 'error!';
}
}
And I still have some functions similar to that, it almost the same code I'm trying to make it simple, is it possible to make it in 1 function only?

Try:
function maxval(x,maxval) {
if(x >= '1' && x <= '50'){
var sum = (maxval+10)* x;
hasil.value = 'Rp.'+parseFloat(sum*1000);
}
else if (x >= '51' && x <= '100'){
var sum = (maxval+5)* x;
hasil.value = 'Rp.'+parseFloat(sum*1000);
}
else if(x >= '101' && x <= '200'){
var sum = (maxval)* x;
hasil.value = 'Rp.'+parseFloat(sum*1000);
}
else{
hasil.value = 'error!';
}
}
By the way i assumed that maxval increments by 5, Cant get you a better solution without getting more details about functionality.

This would be my implementation. I don't agree with how you're handling your integers, but it's your coding style. I pass in an object of choice that has all of the values that I want. You don't need the logic, just the values. I hope nobody gets mad that I monkeypatch String. I'm assuming that your variable x is a string.
String.prototype.isBetween = function(lower, upper){
int = parseInt(this)
return int >= parseInt(lower) && int <= parseInt(upper)
}
max110 = {0: 120, 1: 115, 2: 110}
max115 = {0: 125, 1: 120, 2: 115}
function max(x, values) {
let sum
hasil.value = ''
if (x.isBetween('1', '50')) {
sum = values['0'] * x
} else if (x.isBetween('51', '100')) {
sum = values['1'] * x
} else if (x.isBetween('101', '200')) {
sum = values['2'] * x
} else {
hasil.value = 'error'
}
hasil.value = hasil.value ? 'error' : 'Rp.'+parseFloat(sum*1000);
}

function max(x, extra) {
var sum_number = extra;
if(x >= '1' && x <= '50'){
sum_number += 120;
}
else if (x >= '51' && x <= '100'){
sum_number += 115;
}
else if(x >= '101' && x <= '200'){
sum_number += 110;
}
if(x < 1 && x > 200){
hasil.value = 'error!';
} else {
hasil.value = 'Rp.'+parseFloat((sum_number) * x *1000);
}
}
parameter extra can be 0 or 5 for function max110 or max115

Basically, you have two function which works the same way and returns the same with different values.
The different values yould be stored in an array and you could use a single function for getting the index and then take the needed value out of the array with that index.
So you need a better organisation of types of the variables, which if uses as number, it should be number and also for comparison, then it should be a number on both sides of the condition.
Use a pure function, which does not alter a state of something, which is not given into the function.
Use a check in the function for unwanted values and exit early with a first check at the lower border, in your case, it is zero and below, return -1, because that is not an index of an array (and it is usually used to denote, that no index is found, like with Array#indexOf).
Then take the upper border for a check end exit early with a index value, no need for continuing else if structures.
At the end return as well -1 for not found index.
Together:
function getValue(x, maxArray) {
var index = getIndex(x);
if (index in maxArray) {
return 'Rp.' + maxArray[index] * x * 1000;
}
return 'error!';
}
function getIndex(x) {
if (!x || x < 0) {
return -1;
}
if (x <= 50) {
return 0;
}
if (x <= 100) {
return 1;
}
if (x <= 200) {
return 2;
}
return -1;
}
var max110 = [120, 115, 110],
max115 = [125, 120, 115];
console.log(getValue(-1, max110));
console.log(getValue(10, max110));
console.log(getValue(10, max115));

Related

I want to check the grade of the students marks , based on average

What's wrong with this code? I tried get marks using array and pass the array in to function parameters and calculate the average in that function.
const marks = [100,100,80];
var summ = 0;
function calculateGrade(){
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}
console.log(calculateGrade(marks));
const sum = marks.reduce((partialSum, a) => partialSum + a, 0);
const marks = [100, 100, 80];
var summ = 0;
//issue one (Tmarks were missing )
function calculateGrade(Tmarks) {
// issues 2 ( <= should be < )
for (let i = 0; i < Tmarks.length; i++) {
summ += Tmarks[i];
}
var avg = summ / Tmarks.length;
if (avg <= 59) {
console.log("F");
} else if (avg >= 60 && avg <= 69) {
console.log("D");
} else if (avg >= 70 && avg <= 79) {
console.log("C");
} else if (avg >= 80 && avg <= 89) {
console.log("B");
} else if (avg >= 90 && avg <= 100) {
console.log("A");
}
}
console.log(calculateGrade(marks));
Following were the issues in your code
You were not getting the parameters in function definition
issues 2 ( <= should be < )
You just added an extra = in your for loop
i<=marks.length
instead of
i<marks.length
So while calculating the sum & average, a garbage value gets added up.
You are very close
const marks = [100, 100, 80];
function calculateGrade(marks) {
let summ = 0;
for (let i = 0; i < marks.length; i++) {
summ += marks[i];
}
const avg = summ / marks.length;
let grade = '';
if (avg < 59) {
grade = 'F';
} else if (avg <= 69) {
grade = 'D';
} else if (avg <= 79) {
grade = 'C';
} else if (avg <= 89) {
grade = 'B';
} else {
grade = 'A';
}
return grade;
}
console.log(calculateGrade(marks));
There are couple of mistakes in your code.
1.
for(let i=0; i<=marks.length;i++)
marks.length is 3. Array index starting from 0.
const marks = [100,100,80];
index 0 is 100.
index 1 is 100.
index 2 is 80.
When you add i<=marks.length, this is equals to i<=3.
= in here will run the loop extra circle and this will return NaN because there are only 3 elements in you array and array indexing is 0 based.
2.
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
avg is out of scope. you have defined avg inside the loop and trying to access it outside of the loop. Anything declared in the loop is scoped to that loop and are not available outside the loop.
3.
console.log(calculateGrade(marks));
Your calculateGrade() function is not accepting any parameters. So you can't pass any parameter into this function.
4.
console.log(calculateGrade(marks));
since calculateGrade() function is not returning any value, this will print nothing. So you don't need to call this inside a console.log();.
I have simplified your code as below.
const marksArr = [100, 100, 80];
calculateGrade(marksArr);
function calculateGrade(marks) {
console.log('calling calculateGrade(marks)...');
var avg = (marksArr.reduce(function(a, b) {
return a + b;
}, 0)) / marksArr.length;
console.log('avg is', avg);
if (avg <= 59) {
console.log('Grade', 'F');
} else if (avg >= 60 && avg <= 69) {
console.log('Grade', 'D');
} else if (avg >= 70 && avg <= 79) {
console.log('Grade', 'C');
} else if (avg >= 80 && avg <= 89) {
console.log('Grade', 'B');
} else if (avg >= 90 && avg <= 100) {
console.log('Grade', 'A');
}
}
` calculateGrade(){
let marks = [100,100,80];
let summ = 0;
let avg = 0;
for(let i = 0; i < marks.length; i++){
summ = summ+marks[i];
avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}`
> array start from 0

Javascript even and odd range

I an trying to solve an online quiz but i don't seem to be able to pass all the tests. here is the question
Given two numbers X and Y, write a function that:
1 returns even numbers between X and Y, if X is greater than Y else it returns odd numbers between x and y
For instance, take the integers 10 and 2 . the function would return all the even numbers between 2 and 10.
Examples:
12, 0 => [2,4,6,8,10]
2, 12 => [3, 5, 7, 9, 11]
0, 0 => [ ]
Here is my code:
function number_game(x, y){
let numbers = [];
if (x > y){
for (let i = y; i <= x; i++){
if (i > y){
numbers.push(i);
}
}
}else{
for (let i = x; i <= y; i++){
if (i > x){
numbers.push(i);
}
}
}
const result = numbers.filter(function(num){
return x > y ? num % 2 === 0: num % 2 === 1;
});
return result;
}
While not written optimally, your code is essentially OK, except that it includes the higher number in the result. You're skipping the lower number with your if (i > y) test, although it would be simpler to just start your loop at y + 1.
To exclude the higher number, simply change the repetition criteria from <= to <.
It would also be simpler to perform the even or odd test in those loops.
function number_game(x, y) {
let numbers = [];
if (x > y) {
for (let i = y + 1; i < x; i++) {
if (i % 2 == 0) {
numbers.push(i);
}
}
} else {
for (let i = x + 1; i < y; i++) {
if (i % 2 == 1) {
numbers.push(i);
}
}
}
return numbers;
}
console.log(number_game(12, 0));
console.log(number_game(2, 12));
console.log(number_game(0, 0));
console.log(number_game(3, 13));
console.log(number_game(1, 1));
Because I'm such a damn sucker for code golfing:
const number_game = (x, y) => {
const min = Math.min(x, y), max = Math.max(x, y);
return Array.from(Array(max - min), (_, i) => i + min).slice(1)
.filter(v => v % 2 == (x < y));
};
Perhaps something like this could help.
function number_game(x, y) {
let result = [];
let min=0, max=0;
if(x==y) {
return result;
} else if (x > y) {
min = y;
max = x;
} else {
min = x;
max = y;
}
for (let i = min; i <= max; i++){
if (i%2===0 && x > y && i!=min && i!=max) {
result.push(i);
}
if (i%2===1 && x < y && i!=min && i!=max) {
result.push(i);
}
}
return result;
}
console.log(number_game(12,0));
console.log(number_game(2,12));
console.log(number_game(0,0));
console.log(number_game(13,1));
console.log(number_game(3,13));
console.log(number_game(1,1));
console.log(number_game(1,1000));
console.log(number_game(3,1300));
Instead of generating all the numbers, and then filtering them, you can generate just the numbers that you need:
function number_game(x, y) {
const start = Math.min(x, y);
const end = Math.max(x, y);
const base = x > y ? 2 - start % 2 : start % 2 + 1; // how much you need to add, to get from start to the first number in the result
const numbers = [];
for(let i = start + base; i < end; i+= 2) numbers.push(i);
return numbers;
}
console.log(JSON.stringify(number_game(9, 1)));
console.log(JSON.stringify(number_game(1, 9)));
console.log(JSON.stringify(number_game(12, 2)));
console.log(JSON.stringify(number_game(2, 12)));
console.log(JSON.stringify(number_game(12, 1)));
console.log(JSON.stringify(number_game(1, 12)));
console.log(JSON.stringify(number_game(2, 2)));
function returnOddOrEven(x,y){
// return empty array if both x and y are equal to 0
let mixedArr = [];
if (x ===0 && y===0){
return [];
}
// first condition of x greater than y
else if ( x > y){
for (var i = 1; i < x; i++){
if( i % 2 === 0){
mixedArr.push(i)
}
}
}
// second condition of y > x
else if( y > x){
for (var i = 1; i < y; i++){
if(i > 1 && i % 2 === 1){
mixedArr.push(i)
}
}
}
return mixedArr;
}
function number_game(x, y) {
var numArray = new Array();
if (x > y) {
for (i=y+1; i<x; i++) {
if (i%2 == 0) {
numArray[numArray.length] = i;
}
}
} else {
for (i=x+1; i<y; i++) {
if (i%2 != 0) {
numArray[numArray.length] = i;
}
}
}
return numArray;
}

Why When I Convert a 22+ Digit Decimal Number To Hexadecimal The Result is 10?

So I wrote a code that converts from decimal to hexadecimal and when i entered a 22 digit number or more the result is always 20 can someone explain why is this happening? here is the code, i went to online sites to convert such a number and it works there but why not with me?:
function convert(x) {
x = parseFloat(x);
var mod = 0;
var sum = "";
var FinalSum = "";
var y;
var str;
var slpha;
var beta;
while (x !== 0) {
mod = x % 16;
if (mod == 10) {
sum += "a";
} else if (mod == 11) {
sum += "b";
} else if (mod == 12) {
sum += "c";
} else if (mod == 13) {
sum += "d"
} else if (mod == 14) {
sum += "e";
} else if (mod == 15) {
sum += "f";
} else {
sum += mod;
}
x = parseInt(x / 16);
} //while loop end.
/* everything is right
till now but you have to
deal with the reverse issue */
str = sum;
alpha = sum.length - 1;
beta = alpha + 1;
while (alpha !== -1) {
FinalSum += str.slice(alpha, beta);
beta--;
alpha--;
} //while loop end.
console.log(FinalSum);
}
convert(1212312313123123123456);

How do you return a value if it exceeds a certain number?

I am making a app for a board game for school, the game is based on Game of the Goose. In this game once you are on a certain spot and you exceed the highest number it sets you back the value that is left. For example, if you are at 64 and you roll 4 you return to spot 66 because 67 is the highest number. I'm using a math.random and a math.floor to add a number to the player from 1 to 6.
*edit:
Here is the code i am writing, it's a bit sloppy though, sorry for that.
var players = [
{
name: "Speler 1",
positie: 0
},
{
name: "Speler 2",
positie: 0
},
{
name: "Speler 3",
positie: 0
},
{
name: "Speler 4",
positie: 0
}
];
var position = 0;
var currentPlayer = players[position];
function rolClick(){
if (position >= players.length){
position = 0;
};
currentPlayer = players[position++];
var rollen = Math.floor(Math.random() * 6) + 1;
if (rollen === 1){
currentPlayer.positie += 1;
}else if(rollen === 2){
currentPlayer.positie += 2;
}else if(rollen === 3){
currentPlayer.positie += 3;
}else if(rollen === 4){
currentPlayer.positie += 4;
}else if(rollen === 5){
currentPlayer.positie += 5;
}else if(rollen === 6){
currentPlayer.positie += 6;
}};
Suppose the variable that you are increasing is called current.
function getRandomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var highest = 67;
current += getRandomBetween(1, 6);
if(current > highest) return highest-1;
Something like this..
function onRoll(this) {
currentVal=this.value;
x=Math.random();//Ensure you have your limitations of random number in place;
newVal=currentVal+x;
if(newVal>66)//whatever your limit
return 66;
else
return newVal;
}
This script do what you want (I think):
maxValue = 67
dice = Math.floor((Math.random() * 10) + 1)
oldValue = 64
if(oldValue + dice > maxValue){
alert("You reached the maximum. Your Value is set to " + (maxValue-1))
newValue = maxValue-1
}else{
newValue = oldValue+dice
}
You should read the if Statements...
here you can read and learn it:
http://www.w3schools.com/js/js_if_else.asp

Javascript return not working

I have this code:
function get_id_from_coords (x, y)
{
x = parseInt(x);
y = parseInt(y);
if (x < 0)
{
x = (x + 6) * 60;
}
else
{
x = (x + 5) * 60;
}
if (y < 0)
{
y = (y + 6) * 60;
}
else
{
y = (y + 5) * 60;
}
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
alert (parseInt($(this).attr('id')));
return parseInt($(this).attr('id'));
}
}
});
}
alert(get_id_from_coords(x, y));
However, from this code I get two popups:
First, from inside the function, I get the proper value (like 63), but then, when I alert the return value, I just get undefined.
You get undefined as you function doesn't return - the last statement is a call to each function and it's not a return statement. If you put a return, e.g.
...
return $('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
alert (parseInt($(this).attr('id')));
return parseInt($(this).attr('id'));
}
}
});
it will return something - in this case, based on the docs:
http://api.jquery.com/jQuery.each/
The method returns its first argument, the object that was iterated.
it will return the children of #planets.
If you want to find some value specifically using each, then you can do something like this:
...
val toRet;
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
toRet = parseInt($(this).attr('id'));
}
}
});
return toRet;

Categories

Resources