Simplifying IF/ELSE condition - javascript

I want to ask how can I simplify my code? It seems hard to read and has too much if-else condition here. Any way to simplify the code?
if (e.shiftKey && this.idx > 0) {
this.idx= this.idx - 1;
} else if (!e.shiftKey && this.idx < trapFocus.length - 1) {
this.idx = this.idx + 1;
} else if (!e.shiftKey && this.idx < trapFocus.length + 1) {
this.idx= this.idx - 2;
} else if (e.shiftKey && this.idx > - 1) {
this.idx= this.idx + 2;
}

You can simply separate the condition using separate if-else
if (e.shiftKey){
if(this.idx > 0) this.idx = this.idx - 1;
else if(this.idx > -1) this.idx = this.idx + 2;
} else {
if(this.idx < trapFocus.length - 1)) this.idx = this.idx + 1;
else if(this.idx < trapFocus.length + 1) this.idx < trapFocus.length + 1
}

This first thing you could do is to factor out e.shiftKey and use += and -= operators
if(e.shiftKey)
{
if(this.idx > 0)
{
this.idx -= 1;
}
else if(this.idx > -1)
{
this.idx += 2;
}
}
else{
if(this.idx < trapFocus.length - 1)
{
this.idx += 1;
}
else if(this.idx < trapFocus.length + 1)
{
this.idx -= 2;
}
}
If you ever want to go with ternaries:
this.idx += e.shiftKey ? (
this.idx > 0 ? -1 :
this.idx > -1 ? 2 : 0
) : (
this.idx < trapFocus.length - 1 ? 1 :
this.idx < trapFocus.length + 1 ? -2 : 0
);
Note that this is not necessarily more readable, it just takes up less space.

You can get it a bit more succinct by using the fact that your if clauses logically imply each other partly.
if e.shiftKey is true you change something if this.idx is 0 or more and if e.shiftKey is false you change something only if this.idx < trapFocus.length + 1:
let offset = 0;
if (e.shiftKey){
if (this.idx >= 0) (this.idx ? offset = -1 : offset = 2)
} else {
if (this.idx < trapFocus.length + 1)
(this.idx < trapFocus.length - 1 ? offset = 1 : offset = -2)
}
this.idx += offset;
It is not necessarily much more readable.

Related

Conditional exercise addWithSurcharge

I can't figure why b arguments greater than 20 don't work here. See results
Exercise:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
Example: addWithSurcharge(10, 30) should return 44.
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}
Issue
The reason is that you condition else if (10 < a <= 20) evaluates to true.
10 < a will be evaluated to true
true <= 20 will be evaluated to true.
So the number will evaluated as boolean and every number greater than 0 evaluates to true. That's the reason why true <= 20 evaluates to true
You can check this by this snippet
console.log(true <= 20)
console.log(true <= 0)
console.log(true <= -3)
Solution
To define a range you should use the && operator like this
else if (10 < b && b <= 20)
Then it will
check if 10 < 30 evaluate to true
check if 30 <= 20 evaluate to false
true && false will evaluate to false
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a && a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b && b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}
console.log(addWithSurcharge(10,30))

Stuck in an Infinite Loop with Multiple If Conditions inside a loop

Can you please let me know why this code is generating an infinite loop? I have tried to limit the steps between > min ) && (i <= logic but it's still sticking in the loop.
var min = -9.00;
var max = 14.00;
for (var i = min; i < max;) {
console.log(i);
if((i > min ) && (i <= -2.00)) {i += (0.25);}
if((i > -2.00 ) && (i <= 0.00)){i += (0.5);}
if((i > 0.00 ) && (i <= 6.00)) {i += (0.25);}
if((i > 6.00 ) && (i <= max)) {i += (0.5);}
}
Yes you have an infinite loop. Because i = -9.00 and your first if is i > min which min = -9.00 its the same not greather. just change > to >=
var min = -9.00;
var max = 14.00;
for (var i = min; i < max;) {
console.log(i);
if((i >= min ) && (i <= -2.00)) {i += (0.25);}
if((i > -2.00 ) && (i <= 0.00)){i += (0.5);}
if((i > 0.00 ) && (i <= 6.00)) {i += (0.25);}
if((i > 6.00 ) && (i <= max)) {i += (0.5);}
}

Stuck programming Conway's "Game of Life" in JS

We have to program a JavaScript version of Conway's Game of Life for a school project, but we're stuck on looping the edges. The whole thing works fine, but the function that calculates the number of neighbors doesn't work on the cells that are on the edges (because it has to evaluate values outside of the array, which are undefined). We've tried several options, but they all alter the functionality of the rest of the program.
What should we add for it to work on the edges of the grid?
var totalNeighbors = function(x, y) {
var total = 0;
if (x > 0 && cells[(x - 1)][y] == 1) {
total++;
}
if (x < (width - 1) && cells[x + 1][y] == 1) {
total++;
}
if (y > 0 && cells[x][y - 1] == 1) {
total++;
}
if (y < (height - 1) && cells[x][y + 1] == 1) {
total++;
}
if (y > 0 && x > 0 && cells[x - 1][y - 1] == 1) {
total++;
}
if (y > 0 && x < (width - 1) && cells[x + 1][y - 1] == 1) {
total++;
}
if (y < (height - 1) && x > 0 && cells[x - 1][y + 1] == 1) {
total++;
}
if (y < (height - 1) && x < (width - 1) && cells[x + 1][y + 1] == 1) {
total++;
}
return total;
};
Thanks!
I'd go with something more like this:
As you can see, I refactored a little bit.
var isvalid = function(x, y) {
/*
* This returns 1 if cells[x][y] == 1.
* Otherwise, we return 0.
* NOTE: If cells[x, y] is out of bounds, we return 0.
* GLOBALS USED: cells, width, and height.
*/
//This returns true if (index < size && index >= 0)
//Used to check that index is not an invalid index.
var inbounds = function (size, index) {
return (index >= 0 && index < size);
};
//given point is out of bounds
if (!inbounds(width, x) || !inbounds(height, y)) {
return 0;
}
//everything is good
return (cells[x][y] === 1) ? 1 : 0;
};
var totalNeighbors = function(x, y) {
var total = 0;
//cells[x-1][y]
total += isvalid(x-1, y);
//cells[x + 1][y]
total += isvalid(x+1, y);
//cells[x][y - 1]
total += isvalid(x, y-1);
//cells[x][y + 1]
total += isvalid(x, y+1);
//cells[x - 1][y - 1]
total += isvalid(x-1, y-1);
//cells[x + 1][y - 1]
total += isvalid(x+1, y-1);
//cells[x - 1][y + 1]
total += isvalid(x-1, y+1);
//cells[x + 1][y + 1]
total += isvalid(x+1, y+1);
return total;
};
PS: Your original code sample is 37 lines without comments. My code sample is 52 lines with comments and 33 lines without comments.
As near as I can figure, this way is cleaner and shorter. ;)

How to detect last device motion event using javascript?

Good day all,
I am trying to capture the values of accelerationIncludingGravity in javascript just before it stops generating any more, that is, when the device is stationary. I know that there is an event called motionEnded generated in Xcode to capture this, but I would like to perform the same thing using javascript to make it device independent.
Thanks in advance for the effort.
Here is the full HTML code ... Most of it is for measuring the last DeviceMotion event...
<script type="text/javascript">
var x = 0, y = 0, vx = 0, vy = 0, ax = 0, ay = 0, accX = 0, accY = 0, accZ = 0, readingStarted = 0, readingCompleted = 0, buttonPress = 0, test = 0, toleranceCounter = 0;
function throttle (callback, limit) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait) { // If we're not waiting
callback.call(); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}
function myFunction() {
if(buttonPress == 0)
{
readingStarted = 0;
readingCompleted = 0;
toleranceCounter = 0;
test = 0;
window.addEventListener('devicemotion', throttle (handleMotionEvent, 200), false);
}
if ((buttonPress < 6) && ((readingStarted == 0) || (readingCompleted ==1)))
{
readingStarted = 0;
readingCompleted = 0;
toleranceCounter = 0;
buttonPress = buttonPress + 1;
}
document.getElementById("buttonp").innerHTML = buttonPress;
document.getElementById("test").innerHTML = test;
}
function handleMotionEvent(e)
{
test = test + 1;
if (readingCompleted == 1)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
passToPHP2(accX, accY, accZ);
}
else if ( (readingStarted == 0) && (readingCompleted == 0) &&
(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = e.accelerationIncludingGravity.x;
accY = e.accelerationIncludingGravity.y;
accZ = e.accelerationIncludingGravity.z;
readingStarted = 1;
if ( e.rotationRate ) {
document.getElementById("rotationAlpha").innerHTML = e.rotationRate.alpha;
document.getElementById("rotationBeta").innerHTML = e.rotationRate.beta;
document.getElementById("rotationGamma").innerHTML = e.rotationRate.gamma;
}
}
else if ( (readingStarted == 1) && (readingCompleted == 0) && (toleranceCounter < 5) &&
!(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
toleranceCounter = toleranceCounter + 1;
}
else if ( (readingStarted == 1) && (readingCompleted == 0) && (toleranceCounter == 5) &&
!(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
passToPHP(accX, accY, accZ);
readingCompleted = 1;
}
else if ( (readingStarted == 1) && (readingCompleted == 0) &&
(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
toleranceCounter = 0;
}
document.getElementById("accelerationX").innerHTML = accX;
document.getElementById("accelerationY").innerHTML = accY;
document.getElementById("accelerationZ").innerHTML = accZ;
}
function passToPHP(x, y, z)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost/acc.php?accX=" + x + "&accY=" + y + "&accZ=" + z, true);
xhttp.send();
}
function passToPHP2(x, y, z)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost/acc2.php?accX=" + x + "&accY=" + y + "&accZ=" + z, true);
xhttp.send();
}
</script>

howto convert a number to a clever number with specific length and k, m, b

for example I have this number:
1,234,567.89
And I want to convert this number to a number with a specific length like these:
1M
01M
1.2M
1.23M
1.234M
1.2346M
1.23457M
1,234,568
01,234,568
1,234,567.9
1,234,567.89
Is there any javascript function, plugin or something for doing this in such a way (with K, M, B...)?
I don't understand your downvotes because this a not a duplicated question und I found NOTHING similar. So i made it by myself and it works ;)
function number(num, size) {
var s = num;
var l1 = s.toString().length;
if (l1 > size && num > 1) s = Math.floor(num);
var l2 = s.toString().length;
if (l2 > size) {
if (num >= 1e3 && num < 1e6) {
s = num / 1e3;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'k';
} else if (num >= 1e6 && num < 1e9) {
s = num / 1e6;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'M';
} else if (num >= 1e9 && num < 1e12) {
s = num / 1e9;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'G';
} else if (num >= 1e12 && num < 1e15) {
s = num / 1e12;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'T';
} else if (num >= 1e15 && num < 1e18) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'P';
} else if (num >= 1e18 && num < 1e21) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'E';
} else if (num >= 1e21 && num < 1e24) {
s = num / 1e21;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Z';
} else if (num >= 1e24 && num < 1e27) {
s = num / 1e24;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Y';
}
}
var l3 = s.toString().length;
if (l3 > size) s = '-';
var s = s.toString();
while (s.length < size) s = s.charAt(0) == '-' ? '-' + s : '0' + s;
var startZeros = /^(0)\1+/.exec(s),
startZerosCount = (startZeros != null) ? startZeros[0].length : 0,
decimalCount = (num.toString().split('.')[1] || []).length;
if (startZerosCount >= 2 && decimalCount > 0 && s.indexOf('.') < 0) {
var decimals = num.toString().split('.')[1],
movedDigits = Math.min(startZerosCount, decimalCount),
lastChar = s.substring(s.length - 1);
if (isNaN(lastChar)) {
s = s.substring(0, s.length - 1);
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
s += lastChar;
} else {
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
}
}
return s;
}
The output for 784432432.9999 is:
-
--
---
784M
0784M
784.4M
784.43M
784.432M
784432432
0784432432

Categories

Resources