Link to Codepen
For a math project due very soon.
I've tried to apply the DRY concept, but I don't know how. I started to write a function that would apply for all of the numbers, but halfway through it I realized there's no way it would work. The anonymous functions need to be changed I know that, yet I can't right now as I don't know another way to implement it.
document.querySelector(".button").addEventListener("click", function) {
num = document.getElementById('something');
if (num != null && num === document.getElementById("zero")) {
calculation = calculation.concat("0");
} else if (num != null && num === document.getElementById("one")) {
calculation = calculation.concat("1");
} else if (num != null === && num document.getElementbyId("two")) {
calculation = calculation.concat("2");
} else if (num != nul && num === document.getElementbyId("three")) {
calculation = calculation.concat("3");
} else if (num != nul && num === document.getElementbyId("four")) {
calculation = calculation.concat("4");
} else if (num != nul && num === document.getElementbyId("five")) {
calculation = calculation.concat("5");
} else if (num != nul && num === document.getElementbyId()) {
calculation = calculation.concat("6");
}
}
Each number is inside a button which is inside a table. They also have id's identifying which number they are. I'm not looking for code, don't want to plagiarize anything. Just looking for suggestions on what I could do differently.
Your easiest method will be writing a common function:
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener(
"click",
function() {
var current_value = this.innerHTML; //typed single number
var display_value = document.getElementById('display').value; //the value on the calculator display
var new_value = display_value + '' + current_value; //+''+ to make it string
document.getElementById('display').value = new_value;
});
}
Try this and add exceptions and calculation functions with same method as above by filtering '+','-', etc. values.
i think its easier if you use jquery..just a suggestion.
please see the fiddle.
i have added a class 'show' to all buttons which we want to display on the screen on click and class 'calc' for all operator buttons..replaced your display javascript with the following jquery
var calculation='';
$('button.show').click(function(){
calculation = calculation.concat($(this).text());
$('#screen').text(calculation);
});
And also added scripts for the calculation
Please see the fiddle Updated Fiddle
Related
there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);
I'm trying to create a filter with javascript with 4 input fields so I'm guessin 16 combinations of possible searches. I can search all 4 at once or 1 input at a time but for some reason when I add other statements I get wierd results. Is there a better way to implement a filter?
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if (unfilteredFloorplans[i].city == req.body.cityName &&
unfilteredFloorplans[i].building == req.body.buildingName &&
unfilteredFloorplans[i].bedrooms == req.body.minBedroom &&
unfilteredFloorplans[i].baths == req.body.maxBathroom) {
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
So now I need to write 15 more if statements? Rather than copy them in I'd like to ask if this is correct and does anyone know how you could implement this with a switch statement?
Edit: And when I say 15 more statements I mean one for if they just pick city, andother if they pick city and bedrooms etc. It just seems inefficient
A minimal fix would be to combine your "and" with "or", but note how this turns the code into a hard-to-read mess:
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if ((req.body.cityName == '' || unfilteredFloorplans[i].city == req.body.cityName) &&
(req.body.buildingName == '' || unfilteredFloorplans[i].building == req.body.buildingName) &&
(req.body.minBedroom == '' || unfilteredFloorplans[i].bedrooms == req.body.minBedroom) &&
(req.body.maxBathroom == '' || unfilteredFloorplans[i].baths == req.body.maxBathroom)) {
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
(BTW, this looks like a good exercise for combining conjunctions with disjunctions.)
Edit I'd recommend to put the filtering into a separate function, and to introduce an additional helper function. Also, use a more consistent naming and use "===" instead of "==".
function filterByEquality(formValue, dataValue) {
if (formValue === '') return true;
if (formValue === dataValue) return true;
return false;
}
function filterFloorplan(form, data) {
if (!filterByEquality(form.city, data.city)) return false;
if (!filterByEquality(form.building, data.building)) return false;
if (!filterByEquality(form.minBedrooms, data.bedrooms)) return false;
if (!filterByEquality(form.maxBathrooms, data.bathrooms)) return false;
return true;
}
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if (filterFloorplan(req.body, unfilteredFloorplans[i]);
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
You can reduce this code even further by learning about the Array.filter method. And you should fix the bug where for some fields should use ">=" or ">=" instead of "===". But I'll leave those things as an exercise.
Here's a simplified example of what your code may look like (in this example, I hardcoded the values representing the input choices):
var unfilteredFloorplans = [{
city: 'NY',
building: 'A',
bedrooms: 2,
baths: 1,
}];
var filteredFloorplans = unfilteredFloorplans.filter(
function(el) {
return el.city === 'NY' && el.building === 'A' && el.bedrooms >= 1 && el.baths >= 1;
}
);
console.log(filteredFloorplans);
The anonymous function being called inside the filter can be replaced with a named function like so:
function filterFloorplans(floorplan) {
return floorplan.city === 'NY' && floorplan.building === 'A' && floorplan.bedrooms >= 1 && floorplan.baths >= 1;
}
var filteredFloorplans = unfilteredFloorplans.filter(filterFloorplans);
You'll likely want to use this route since you can have any combination of the 4 input choices. As such, you'll want the filterFloorplans function to be "built-up" from other, smaller checks:
function testCity(userInputCity, floorplanCity) {
return userInputCity ? userInputCity === floorplanCity : true;
}
function filterFloorplans(floorplan) {
return testCity('NY', floorplan.city) && floorplan.building === 'A' && floorplan.bedrooms >= 1 && floorplan.baths >= 1;
}
This should be enough to get you started; feel free to comment if you get stuck
I have an angularjs function whereby the hope is to take a row away from $scope.model.insuredContact using the splice function. Unfortunately right now it seems the line of code below simply returns the row that hypothetically would be taken away...if that makes any sense? Meaning it just returns the row we are try eliminate but it doesn't really take it out of the array. How to do? Any help would be most appreciated.
$scope.txtChanged = function (i) {
var x = $scope.model.insuredContact[i];
if ((x.ContactName === '' || x.ContactName == undefined) && (x.ContactEmail === '' || x.ContactEmail == undefined) && (x.ContactPhone === '' || x.ContactPhone == undefined)) {
if (i == $scope.model.insuredContact.length - 1) { return; }
$scope.model.insuredContact = $scope.model.insuredContact.splice(i, 1);
}
}
I'm writing a one-line calculator, that has the basic functions (+ - * /). I have done this before, but now I keep getting wrong answers, and I can't find my mistake. Here is my code:
var seq = document.getElementById('sequence').value;
var allNums = [];
var i = 0, allSigns = [];
var currentNums = "";
for (i = 0; i< seq.length; i++)
{
if (seq[i] != "+" && seq[i] != "-" && seq[i] != "*" && seq[i] != "/")
{
currentNums+=seq[i];
}
else
{
allNums.push(Number(currentNums));
currentNums="";
allSigns.push(seq[i]);
}
}
allNums.push(Number(currentNums));
var result = 0;
for (i = 0; i < allNums.length; i++)
{
if (allSigns[i] == '+')
result+=Number(allNums[i]);
else if (allSigns[i] == "-")
result-=Number(allNums[i]);
else if (allSigns[i] == "*")
result*=Number(allNums[i]);
else if (allSigns[i] == "/")
result/=parseInt(allNums[i]);
else
{
alert("The result is: " + result);
break;
}
}
All of this code is in a function, called calculate. The func is triggered by a button, and the sequence comes from an input.
Though there are numerous shortcomings with this simple calculator that may or may not be a problem (depending on what you want to do with it), one issue is that your allSigns array values aren't being associated with the correct allNums array values.
Take a look at this example. In the console, you can see that the sign associated with the 6 is the plus sign, while the operator associated with 2 is undefined. This isn't what we want, of course. What we want is to add the two to the six.
The fix for this issue would be always adding allNums[0] to the result from the start. This sets up our result to be operated upon by anything following it. In this case, we start off with 6.
Next what we need to do is shift the position of each value of allSigns down by one, lining up the operator with the value after it, and not before it. So, in the example above, we'd have + associated with 2, so it'd add the two to the six.
This JSFiddle shows the fix for this specific case.
http://jsbin.com/obasix/3/edit
There are not as many signs as numbers. So therefore, if there are 2 numbers and 1 sign, it will calculate 5 + and then end.
You should start with the result bring the first number.
And then iterate with the remaining numbers and calculate accordingly.
var seq = "5+4";
var allNums = [];
var i = 0, allSigns = [];
var currentNums = "";
for (i = 0; i< seq.length; i++)
{
if (seq[i] != "+" && seq[i] != "-" && seq[i] != "*" && seq[i] != "/")
{
currentNums+=seq[i];
}
else
{
allNums.push(Number(currentNums));
currentNums="";
allSigns.push(seq[i]);
}
}
allNums.push(Number(currentNums));
var result = allNums[0];
for (i = 1; i <= allNums.length; i++)
{
if (allSigns[i-1] == '+')
result+=Number(allNums[i]);
else if (allSigns[i-1] == "-")
result-=Number(allNums[i]);
else if (allSigns[i-1] == "*")
result*=Number(allNums[i]);
else if (allSigns[i-1] == "/")
result/=parseInt(allNums[i]);
else
{
alert("The result is: " + result);
break;
}
}
Try this library https://github.com/notshekhar/calculate.js
Example
<script src="https://raw.githubusercontent.com/notshekhar/calculate.js/main/calculate.js"></script>
<script>
let add = calculate(1, 1, "+") // add -> 2
let sub = calculate(1, 1, "-") // sub -> 0
let mul = calculate(1, 1, "*") // mul -> 1
let div = calculate(1, 1, "/") // div -> 1
let mod = calculate(1, 1, "%") // mod -> 0
</script>
function ord(string) {
var str = string + '',
code = str.charCodeAt(0);
if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
var hi = code;
if (str.length === 1) {
return code; // This is just a high surrogate with no following low surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know }
var low = str.charCodeAt(1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know
}
return code;
}
}
$(document).ready(function () {
var maxTxtNumber = 8;
var arrTxtNumber = new Array();
var txtvalues = new Array();
var arr = {};
$('.numericonly').keypress(function (e) {
var t = $(this).val();
var k = e.which;
delete arr[8];
if ((e.which >= 49 && e.which <= 55) || e.which == 8) {
if (e.which == 8) {
var s = new String(t);
s = s.charCodeAt(0);
delete arr[s];
}
if (arr[k]) {
e.preventDefault();
} else {
arr[k] = e.which;
}
} else {
e.preventDefault();
}
});
});
The code works on Firefox but not on IE and Chrome?
Other browsers use e.keyCode to tell you which key was pressed. Cross-browser:
var k = e.keyCode || e.which;
Also make sure you use k rather than repeating e.which every time.
All that code is not required. If you want to test that an input's value is only digits, then something like the following will do:
<input type="text" onblur="check(this);" ...>
function check(el) {
if (!isDigits(el.value)) {
alert('Hey!!\nThe element you just left should only contain digits');
}
}
function isDigits(s) {
return /^\d*$/.test(s);
}
It's much more friendly to give the user a hint about the format you require and wait until they either leave the control or submit the form before offering a warning about invalid values. You really don't care how the user gets to a valid value, just so long as it's valid when the form is submitted.
And you must validate on the server again.
I recommend running your code through a validator such as http://www.jslint.com/ to make sure that everything adheres to universal standards.