Building a calculator and I'm implementing cube roots and square roots, but when reversed by squaring them or cubing them respectively, it is off by a very small, but it is noticeable and ugly in the calculator when there are several zeros and a 1 after it. Any way to prevent this, but still make the calculator accurate.
function click22() {
if (vi === 0) {
reactant = Math.sqrt(reactant);
} else if (vi !== 0 && tn === 0) {
reactant2 = Math.sqrt(reactant2);
} else if (vi !== 0 && tn !== 0) {
reactantspec = Math.sqrt(reactantspec);
}
}
function click23() {
if (vi === 0) {
reactant = Math.cbrt(reactant);
} else if (vi !== 0 && tn === 0) {
reactant2 = Math.cbrt(reactant2);
} else if (vi !== 0 && tn !== 0) {
reactantspec = Math.cbrt(reactantspec);
}
}
if (vi === 0 && reactant != "0"){
document.getElementById('result').innerHTML = reactant;
} else if (vi > 1 && reactant2 != "" && tx === 0) {
document.getElementById('result').innerHTML = reactant2;
} else if (vi > 1 && tx > 0) {
document.getElementById('result').innerHTML = reactantspec;
}
}
Related
I just wrote this piece of code that does the thing it's supposed to do, although it's really messy and pretty repetitive and I'm wondering how can I make it much shorter and concise.
if(id==1 && player == "playerOne"){
Object.assign(playerOne, fighters[0])
}else if(id==1 && player =="playerTwo"){
Object.assign(playerTwo, fighters[0])
}
if(id==2 && player == "playerOne"){
Object.assign(playerOne, fighters[1])
}else if(id==2 && player =="playerTwo"){
Object.assign(playerTwo, fighters[1])
}
if(id==3 && player == "playerOne"){
Object.assign(playerOne, fighters[2])
}else if(id==3 && player =="playerTwo"){
Object.assign(playerTwo, fighters[2])
}
if(id==4 && player == "playerOne"){
Object.assign(playerOne, fighters[3])
}else if(id==4 && player =="playerTwo"){
Object.assign(playerTwo, fighters[3])
}
if(id==5 && player == "playerOne"){
Object.assign(playerOne, fighters[4])
}else if(id==5 && player =="playerTwo"){
Object.assign(playerTwo, fighters[4])
}
if(id==6 && player == "playerOne"){
Object.assign(playerOne, fighters[5])
}else if(id==6 && player =="playerTwo"){
Object.assign(playerTwo, fighters[5])
}
if(id==7 && player == "playerOne"){
Object.assign(playerOne, fighters[6])
}else if(id==7 && player =="playerTwo"){
Object.assign(playerTwo, fighters[6])
}
if(id==8 && player == "playerOne"){
Object.assign(playerOne, fighters[7])
}else if(id==8 && player =="playerTwo"){
Object.assign(playerTwo, fighters[7])
}
if(id==9 && player == "playerOne"){
Object.assign(playerOne, fighters[8])
}else if(id==9 && player =="playerTwo"){
Object.assign(playerTwo, fighters[8])
}
Thank you in advance!
Assuming
a) there are no more than two players
b) you don't care that this code handles id < 1 and id > 9
It looks to me like you could reduce this to a single line.
Object.assign(player == "playerOne" ? playerOne : playerTwo, fighters[id - 1])
What if you rewrite it to be something along the lines of
if (player == "playerOne") {
p = playerOne
} else if (player =="playerTwo") {
p = playerTwo
}
Object.assign(p, fighters[id - 1])
A for loop might be helpful:
for (let i = 1; i < 10; i++) {
if (id == i && player == "playerOne") {
Object.assign(playerOne, fighters[id - 1]);
} else if (id == i && player == "playerTwo") {
Object.assign(playerTwo, fighters[id - 1]);
}
}
Based on the assumptions in your example, that id must be between 1 and 9 and player can be anything, but must be playerOne or playerTwo:
for (var i = 1; i < 10; i++) {
if (id == i) {
if(player == "playerOne"){
Object.assign(playerOne, fighters[i - 1]);
} else if (player == "playerTwo") {
Object.assign(playerTwo, fighters[i - 1]);
}
}
}
I'm trying to make the input takes only the value 99.999. I don't want to use MaxLength because it would not calculate the length of the decimal digits. I don't want to use any other functions that erase when it doesn't match a specific regex. I want it to stop it in the input.
function IsCurrencyNoMinus1 (e, thisobj, min, max) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (keyCode == 46) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val();
if (ret && (keyCode == 45) && ((thisobj.selectionStart != 0) || (inStr.indexOf('-') != -1)))
ret = false;
if (ret && (keyCode == 46) && (inStr != '' && inStr.indexOf('.') != -1) && !(Math.abs(thisobj.selectionStart - thisobj.selectionEnd) == inStr.length)) {
ret = false;
}
var dotPos = (inStr.indexOf('.') != -1) ? inStr.indexOf('.') : inStr.length;
inStr = inStr.replace(/\,/g, '');
var parts = inStr.split('.');
var maxParts = max.toString().split('.');
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57))) {
if ((parts[0].length >= maxParts[0].length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)
&& (thisobj.selectionStart <= dotPos)) {
ret = false;
}
if (ret && (parts[1] != undefined && parts[1].length >= 2) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)
&& (thisobj.selectionStart > dotPos) && (thisobj.selectionStart <= dotPos + 3))
ret = false;
var firstPos = thisobj.selectionStart < thisobj.selectionEnd ? thisobj.selectionStart : thisobj.selectionEnd;
if (ret && (parts[0].length >= maxParts[0].length) && (parts[1] != undefined && parts[1].length >= 1)
&& ((dotPos - firstPos == 0 && Math.abs(thisobj.selectionStart - thisobj.selectionEnd) < 4)
|| (dotPos - firstPos == 1 && (Math.abs(thisobj.selectionStart - thisobj.selectionEnd) >= 2 && Math.abs(thisobj.selectionStart - thisobj.selectionEnd) < 4))))
ret = false;
}
if (Number(inStr) > max) {
thisobj.value = '';
ret = true;
}
if (Number(inStr) < min) {
thisobj.value = '';
ret = true;
}
// var re = new RegExp(/^\(?-?[0-9]{0,12}(\.[0-9]{0,2})?\)?$/)
// if (!re.test(inStr)) {
// thisobj.value = ""
// }
return ret
}
I found the solution! Please check the code below in case someone needs it.
function Format3DigitDecimal(e, thisobj, min, max)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val()
inStr = inStr.replace(/\,/g, '')
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length == 2) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
return ret
}
Rps game code isn't working. My battle function is supposed to set win to a 1,2, or 3 but it always stays at the default 0. I've checked the other values through the console, and they all seem to be working. here is my code.
function Player(number) {
this.number = number;
this.choice = 0;
}
var player1 = new Player(1);
var player2 = new Player(2);
var win = 0;
var battle = function() {
if (player1.choice === player2.choice) {
win = 3;
} else if (player1.choice + 2 === player2.choice && player1.choice === 1){
win = 2;
} else if (player1.choice + 1 === player2.choice && player1.choice === 1) {
win = 1;
} else if (player1.choice + 1 === player2.choice && player1.choice === 2) {
win = 1;
} else if (player1.choice - 1 === player2.choice && player1.choice === 2) {
win = 2;
} else if (player1.choice - 1 === player2.choice && player1.choice === 3) {
win = 2;
} else if (player1.choice - 2 === player2.choice && player1.choice === 3) {
win = 1;
} else {
alert ('someone pressed the wrong button')
}
}
var Reset = function () {
win = 0;
player1.choice = 0;
player2.choice = 0;
}
$(document).ready(function() {
$(document).keydown(function(event) {
if (event.which === 81) {
player1.choice = 1;
} else if (event.which === 87){
player1.choice = 2;
} else if (event.which === 69){
player1.choice = 3;
} else if (event.which === 37){
player2.choice = 1;
} else if (event.which === 40){
player2.choice = 2;
} else if (event.which === 39){
player2.choice = 3;
}
})
if (player1.choice > 0 && player2.choice > 0) {
battle();
if (win === 1) {
$('.winner').append('<p>player1 wins!</p>')
} else if (win === 2) {
$('.winner').append('<p>player2 wins!</p>')
} else if (win === 3) {
$('.winner').append('<p>It is a draw!</p>')
}
}
})
My html has the div with class 'winner' in it.
Additional question
How do I cancel the keydown function after both players have chosen their options.
Are you giving your player a choice in the Player class you created? It should look like this:
function Player(number, choice) {
this.number = number;
this.choice = choice;
}
I am running into a problem here trying to create a product showcase. Here is my Javascript code: http://codeshare.io/MeJQi
The slider for this code is for is here live at: http://therrd.com/screening.html#tenant-Screening
I can land on this specific page in two ways. One way is a button on another page that changes the default FROM of the slider to land on 15 Units which shows "Product25". Then the other way of landing on this page is where the slider is on default start value of 30 Unit and shows "Product1".
The problem I am having is changing the default product when I land on this page by clicking on the button on the other page, the slider updates but the showing product does not.
I would like to change the default value for the showProduct() based on the slider.
<script>
$(function() {
init();
});
function init()
{
hideAllProducts();
showProduct(1);
vals = {max: 2000, min: 1, def: 20} //use your own values here for max min and def
var param = window.location.href.split("slide=");
slide = isNaN(param[param.length - 1]) ||
param[param.length - 1] > vals.max ||
param[param.length - 1] < vals.min ? vals.def : param[param.length - 1];
//check if there is a url param, if it's a number and if it's in range
$("#screeningSlider").ionRangeSlider({
hide_min_max: true,
keyboard: true,
from: slide,
min: 1,
max: 2000,
step: 0,
grid_num: 4,
prettify_separator: ",",
postfix: " Units",
max_postfix: "+",
force_edges: true,
onStart: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onChange: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onFinish: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onUpdate: function (value) {
document.getElementById("value").innerHTML = (value.from);
}
});
$("#screeningSlider").on("change", function () {
var $this = $(this),
value = $this.prop("value");
productSliderOnChange(value);
});
}
function productSliderOnChange(value)
{
$("#value").text(value);
if(value == 0)
hideAllProducts();
else if ((value > 0) && (value <= 20))
{
hideAllProducts();
showProduct(25);
}
else if ((value >= 21) && (value <= 60))
{
hideAllProducts();
showProduct(1);
}
else if ((value >= 61) && (value <= 120))
{
hideAllProducts();
showProduct(2);
}
else if ((value >= 121) && (value <= 180))
{
hideAllProducts();
showProduct(3);
}
else if ((value >= 181) && (value <= 360))
{
hideAllProducts();
showProduct(4);
}
else if ((value >= 361) && (value <= 580))
{
hideAllProducts();
showProduct(5);
}
else if ((value >= 581) && (value <= 780))
{
hideAllProducts();
showProduct(6);
}
else if ((value >= 781) && (value <= 980))
{
hideAllProducts();
showProduct(7);
}
else if ((value >= 981) && (value <= 1180))
{
hideAllProducts();
showProduct(8);
}
else if ((value >= 1181) && (value <= 1380))
{
hideAllProducts();
showProduct(9);
}
else if ((value >= 1381) && (value <= 1580))
{
hideAllProducts();
showProduct(10);
}
else if ((value >= 1581) && (value <= 1780))
{
hideAllProducts();
showProduct(11);
}
else if ((value >= 1781) && (value <= 1980))
{
hideAllProducts();
showProduct(12);
}
else if ((value > 1981))
{
hideAllProducts();
showProduct(13);
}
else {
hideAllProducts();
showProduct(1);
}
}
function hideAllProducts()
{
$("#Product25").hide();
$("#Product1").hide();
$("#Product2").hide();
$("#Product3").hide();
$("#Product4").hide();
$("#Product5").hide();
$("#Product6").hide();
$("#Product7").hide();
$("#Product8").hide();
$("#Product9").hide();
$("#Product10").hide();
$("#Product11").hide();
$("#Product12").hide();
$("#Product13").hide();
}
function showProduct(productId)
{
var product = "#Product" + productId;
$(product).show();
}
</script>
I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed].
This is my code:
1st function:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
2nd function:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this.
So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something...
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
You can try this :
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
Hope it will help !