Why does my forloop run through my if statment only once? - javascript

I'm writing a calculator in JS and currently I'm writing the '=' function, now I pasted my code below, so I made exp = 5 + 5, everything works fine it tells me that total is 10, now when I do 5+5+5 it still says 10, it's as if the loop ins't working, because I want it to do 5+5 first, update the total to be 10 and then find the + operator again and then add whatever is after the plus, how do I do this? I have no idea why the loop isn't working
All help is appreciated,
Have a nice day,
larwa
function equal(){
var exp = document.form.textview.value;
var expArray = exp.split(/\b/);
console.log(expArray);
let total = 0;
for (let i = 0 ; i < expArray.length; i++){
console.log(expArray[0])
total = parseFloat(expArray[0])
if(i = '+' || '-' || '/' || '*'){
console.log(i);
n = expArray.indexOf(i)
total += parseFloat(expArray[n + 1]);
}
}

There are certain mistakes in your code.
The total should be initialized outside the for loop, otherwise it will generate incorrect total value.
if(i = '+' || '-' || '/' || '*'){, in this instead of using assignment operator i:e =, comparison operator i:e == or === (strict equality operator) should be used. As well separate comparison expressions are required i:e i=== '+' || i=== '-' || i=== '/' || i=== '*'. The i is nothing but index of the array elements, instead of i it should be array element. i:e expArray[i].
let exp = "5 + 5 + 5";
function equal() {
var expArray = exp.split(/\b/);
let total = parseFloat(expArray[0]);
for (let i = 0; i < expArray.length; i++) {
const dig = expArray[i].trim();
if (dig === '+' || dig === '-' || dig === '/' || dig === '*') {
total += parseFloat(expArray[i + 1]);
}
}
return total;
}
console.log(equal());

Try this
for (let i = 0 ; i < expArray.length; i++){
console.log(expArray[0])
total = parseFloat(expArray[0])
if(i == '+' || '-' || '/' || '*'){
console.log(i);
n = expArray.indexOf(i)
total += parseFloat(expArray[n + 1]);
}
The = operator is used for assigning values to a variable, however the == operator is used for comparison between two variables irrespective of the datatype of variable

Related

How to count number of a pattern in a string of words?

This is the question
Given a dictionary of variable names where each name follows CamelCase notation, print the item containing most words. Please note, abbr, like ID , IP are considered one word. i.e. name IPAddress contains two words, IP and Address
singleWordChecking('HelloWorldWideWeb'); the result count should be 4
singleWordChecking('HelloWWW'); the result count should be 2
below are my function on checking single world
function singleWordChecking(word) {
let singleWordCount = 0;
for (let i = 0; i < word.length; i++) {
if (
word[i].toUpperCase() === word[i] &&
word[i + 1].toLowerCase() === word[i + 1]
) {
singleWordCount += 1;
console.log(singleWordCount);
} else if (
word[i].toUpperCase() === word[i] &&
word[i + 1].toUpperCase() === word[i + 1]
) {
return singleWordCount;
}
}
return singleWordCount;
}
singleWordChecking('HelloWorldWideWeb');
singleWordChecking('HelloWWW');
i try with word[i].toUpperCase() === word[i] for verifying the first letter is capitalized,
then if second letter is lowercase
count + 1
however when the word is 'HelloWWW'
the console shows the error of
Cannot read properties of undefined (reading 'toLowerCase')
at singleWordChecking
How do i fix this so that the edge cases can be considering into the function
The reason you are getting the error is because you are going out of bounds of the array by doing your check for the following letter, you will need to add an extra check for:
i + 1 < world.length
However, there are a couple of other issues. For one, you are returning the count when you should be incrementing the count for all capital abbreviations, also checking for 2 capital letters in a row is insufficient because abbreviations can be any length, therefore a possible solution is:
function singleWordChecking(word) {
let singleWordCount = 0;
let isAbbreviation = false;
for (let i = 0; i < word.length; i++) {
if (word[i].toUpperCase() === word[i]) {
if (i + 1 < word.length && word[i + 1].toLowerCase() === word[i + 1]) {
singleWordCount += 1;
isAbbreviation = false;
continue;
}
if (!isAbbreviation) {
singleWordCount += 1;
}
isAbbreviation = true;
}
}
return singleWordCount;
}

Javascript Serial Number CoderByte problem

I'm currently solving a problem at CoderByte. Here's the scenario.
Have the function SerialNumber(str) take the str parameter being passed and determine if it is a valid serial number with the following constraints:
It needs to contain three sets each with three digits (1 through 9) separated by a period.
The first set of digits must add up to an even number.
The second set of digits must add up to an odd number.
The last digit in each set must be larger than the two previous digits in the same set.
If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "224.315.218" then your program should return "true".
Examples
Input: "11.124.667"
Output: false
Input: "114.568.112"
Output: true
Here's my JS code for this problem.
function SerialNumber(str) {
// code goes here
if(str.length < 11) {
return "false";
}
for (let x = 0; x < str.length; x++) {
if(str[x] === '0') {
return "false";
}
}
const first = str[0] + str[1] + str[2];
const second = str[4] + str[5]+ str[6];
if (first % 2 !== 0 || second % 2 === 0) {
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"));
When I input "11.124.667", it will return to false (which is correct). And when I input "114.568.112", it will also return to false (which is not correct). Any tips on how can I obtain this? Thanks for the feedback.
I tried your code and the problem comes from the third return false for the 2nd example, when you set second, you concatenate strings instead of adding numbers, thus %2 is always equal to 0 since
I added console.log before each return false to see which condition failed.
Here's the fixed code in which I added parseInt for first and second
function SerialNumber(str) {
if (str.length < 11) {
console.log("first")
return "false";
}
for (let x = 0; x < str.length; x++) {
if (str[x] === '0') {
console.log("second")
return "false";
}
}
const first = parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2]);
const second = parseInt(str[4]) + parseInt(str[5]) + parseInt(str[6]);
if (first % 2 !== 0 || second % 2 === 0) {
console.log("third")
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
console.log("fourth")
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"))

Cleaning up code in ternary statement [duplicate]

This question already has answers here:
Assign only if condition is true in ternary operator in JavaScript
(13 answers)
Closed 6 years ago.
I am trying to count all the times the letter x and the letter o appear in a string and I'm returning true if they appear the same number of times and false otherwise.
I've completed the problem, but when using a ternary statement it forced me to create an extra condition I didn't need since you seem to need 3 operations in a ternary statement so I just counted every time something else appears in a string. Is there any way I can use a ternary statement without creating an unnecessary condition or would I have to use if statements?
function ExOh(str) {
var ex = 0
var oh = 0
var other = 0
for (var i = 0; i < str.length; i++) {
str[i] === "x" ? ex++ : str[i] === "o" ? oh++ : other++
}
return ex === oh
}
console.log(ExOh("xooabcx$%x73o"));
console.log(ExOh("xooxxo"));
console.log(ExOh("x"));
console.log(ExOh(""));
//wouldn't let me just have one statement after the ternary so I created the other variable.
Why not add the boolean value?
ex += str[i] === "x";
oh += str[i] === "o";
Example
var a = 0;
a += false;
document.write(a + '<br>');
a += true;
document.write(a + '<br>');
While you just need the difference, you can use a single variable and count up for x and down for o. The return value is the not value of count.
function ExOh(str) {
var count = 0, i;
for (i = 0; i < str.length; i++) {
count += str[i] === "x";
count -= str[i] === "o";
}
return !count;
}
document.write(ExOh("xooabcx$%x73o") + '<br>');
document.write(ExOh("xooxxo") + '<br>');
document.write(ExOh("x") + '<br>');
document.write(ExOh("") + '<br>');

Looping through a string of numbers in Javascript

Hey guys working on a problem from CoderBytes. The directions of the following:
Using the JavaScript language, have the function DashInsert(num) insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
Use the Parameter Testing feature in the box below to test your code with different arguments.
So I didn't create a function but here is my road map.
num = 3333333333
arr = num.toString().split("")
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
num.toString().replace(arr[i].toString() + arr[i+1].toString(),
arr[i].toString() + "-" + arr[i+1].toString())
}
}
The thing is when I run this it only puts a dash between the first two threes. I really can't figure out why this is happening. Anyone know where I am going wrong?
Here, this simple solution should do well:
var num = 3434333333
var arr = num.toString().split("");
var finalStr = "";
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
finalStr += arr[i] + "-";
}
else {
finalStr += arr[i];
}
}
simply keep a string for the result, if two consecutive numbers are odd append an extra "-" after the number in the string, otherwise simply append the number and your final string will contain the desired result.
See the DEMO here

Increment operator returns NaN

I am trying to increment a variable using the ++ operator but I keep getting NaN as a result and I'm not sure why. Here is my code:
var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for(var i = 1; i < words.length; i++){
if(words[i].length > 2){
wordCounts["_" + words[i]]++;
}
}
alert(wordCounts.toSource());
The value of wordCounts["_" + words[i]] is initially undefined so when you ++ it, it gives you NaN. Just change your code to:
if (wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]]++;
} else {
wordCounts["_" + words[i]] = 1;
}
Try something like...
var key = "_" + words[i];
if (wordCounts[key]) {
wordCounts[key]++
} else {
wordCounts[key] = 1;
}
You are trying to increment undefined which is giving you NaN.
To be able to use the ++ operator (which takes a number and increments it by one) the target needs to have a number first.
Attempt a check to see if the object is defined, and if not initialize it by setting it's value to 1.
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
Something like:
var wordCounts = {};
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for (var i = 1; i < words.length; i++) {
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
if (words[i].length > 2) {
wordCounts["_" + words[i]]++;
}
}
alert( JSON.stringify( wordCounts ) );
What you're basically doing is
undefined++
Which will result in...
NaN
Try...
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]]++ || 1);
Since NaN is a "falsey" value the || will fall back to 1.
You're trying to increment an object (wordCounts[]++) it's not a number so it can't be incremented, which is why you're getting that error. What are you actually trying to do (in plain English)?

Categories

Resources