js number function for calculator error - javascript

Can anyone explain to me why I get the error message Uncaught ReferenceError: Invalid left-hand side in assignment when I run the below function.
function number(a){
var last = parseInt(stream.charAt(stream.length-1));
if(stream === ''){
stream = a;
}
else if(isNumber(last)){
console.log(last);
stream.charAt(stream.length-1) = last*10 + a;
}
else{
stream += ' '+a;
}
document.getElementById('display').innerHTML = stream;
}

The error is in this line:
stream.charAt(stream.length-1) = last*10 + a;
You can't assign something to stream.charAt(). That function only returns a character.
From what I can gather, you're getting the last character from the stream. If it's a integer, you multiply it by 10, then append a to the stream.
Instead of that, this will give the same result:
stream += '0' + a;
Since you're adding the value back into the array, it really doesn't matter if you multiply a single digit integer with 10, or if you just add a "0" after it.

Your problem seems to be this codepart
stream.charAt(stream.length-1) = last*10 + a;
charAt returns a string, and not a position in your stream (i assume that your stream is a string), so you cant overwrite it.
To solve this you could do something like:
stream = stream.substring(0,stream.length-1)+last*10+a
Im not allowed to comment but Cerbrus answer wont work for last = '0' and will in this case add an additional 0, this should work

the problem is that you can't assign like this
stream.charAt(stream.length-1) = last*10 + a;

Related

Javascript If statements in Zapier Code, "must return a single object or array of objects."

I am trying to do a simple If function in zapier that returns a number between 1-10 based on another number input. for example if the number input is equal to 7200000 it should output 2. so far i have this:
if (inputData.num === '7200000') {
output = '2';
} else {
output = inputData.num;
}
This is giving me the error "You must return a single object or array of objects."
Can anyone help with this?
Thanks in advance :)
I found the solution,
Input Data: ms = TimeEstimate
var d = new Date(1000*Math.round(inputData.ms/1000));
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ',' + pad(d.getUTCMinutes());
console.log(str);
output = [{str}];

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

Recursive function only firing once

In the following function, I don't understand why the counter function only fires once (the figure goes up by a single increment, I want it to count up to homeFigTwo).
function effectFour() {
var homeFigOne = parseFloat($('.home .figure').text());
var homeFigTwo = 23.99;
var plusFigOne = parseFloat($('.home-plus .figure').text());
var plusFigTwo = 28.49;
var homeInc = homeFigOne < homeFigTwo ? .01 : -.01;
var plusInc = plusFigOne < plusFigTwo ? .01 : -.01;
function counterOne(){
if (homeFigOne === homeFigTwo){
return
}else{
homeFigOne = (homeFigOne + homeInc).toFixed(2);
$('.home .figure').text(homeFigOne);
window.setTimeout(counterOne, 100);
}
}
counterOne();
}
This can be seen in context here: http://codepen.io/timsig/pen/NdvBKN.
Many thanks for any help.
toFixed() has a Return value of
A string representing the given number using fixed-point notation.
This means that on the second time that this happens:
homeFigOne = (homeFigOne + homeInc).toFixed(2);
What's really going on is: "16.00" = "16.00" + 0.01 which, in fact, does not possess a toFixed method, as that whole sentence is what.
So what you want is to parseFloat the result of homeFigOne again, because whenever you toFixed it you set it to a string again.
homeFigOne = (parseFloat(homeFigOne) + homeInc).toFixed(2)
Your recursion is working as expected, but on your second call an error is thrown. This is because you convert homeFigOne to a string by using toFixed.
So it basically does this:
first call: values are 15.99 23.99 (both numbers)
second call: values are "16.00" 23.99 (a string and a number)
As the toFixed method is not defined for Strings an exception is thrown. As this happens async in a anonymous function, you prob. didn't noticed.
So my suggestion is to first make the increment, and only cast for your html element:
function effectFour() {
var homeFigOne = parseFloat($('.home .figure').text());
var homeFigTwo = 23.99;
var plusFigOne = parseFloat($('.home-plus .figure').text());
var plusFigTwo = 28.49;
var homeInc = homeFigOne < homeFigTwo ? .01 : -.01;
var plusInc = plusFigOne < plusFigTwo ? .01 : -.01;
function counterOne(){
if (homeFigOne === homeFigTwo){
return
}else{
homeFigOne = homeFigOne + homeInc;
$('.home .figure').text(homeFigOne.toFixed(2));
window.setTimeout(counterOne, 100);
}
}
counterOne();
}
edit:
+ as you are dealing with floats you are better of with >= instead of === for your end criterium

Why can't println(); be used as a variable?

I'm fairly new to Javascript, and am confused on something. Why can't the command "println("..."); be called as a variable such as: var num = println("...");. I could be wrong, and if you are able to, I'd be happy to know how. But after some testing it seems like I can't. My test code is:
function start() {
var SENTINEL = "1 1";
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = println(rollOne + rollTwo);
if(num == SENTINEL) {
println("You did it");
}
}
All it's supposed to do is give to random numbers in a # # form and, if it sees that the numbers are 1,1, it will give a message. It wont give the message and can't seem to view the variable "num" as an actual variable. But when I change the variable num to simply asking the user for a number:
function start() {
var SENTINEL = -1;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = readInt("Enter number");
if(num == SENTINEL) {
println("You did it");
}
}
And type in -1, it triggers the sentinel, thus promptly displaying the message. This is a really roundabout way to ask a simple question but I hope I can get some help. Thank you :)
Why can't the command "println("..."); be called as a variable such as: var num = println("...");
[...] It wont give the message and can't seem to view the variable
If the value returned is unusable, it is most likely undefined; i.e. The function println doesn't explicitly return anything.
In your case, you could try something like this:
var printInt = function(num) { println(num); return num; }
Note, println isn't part of the standard JavaScript language. For modern web browsers, it can be adapted to use (console.log(...)).
var printInt = function(num) { console.log(num); return num; }
And then to adapt to your code:
var num = printInt(rollOne + rollTwo);
But this still won't validate because you're comparing against "1 1" whereas your logic will return 2. JavaScript (as well as many other languages) implicitly uses addition when supplied with two numbers, but concatenation when supplied with at least one string.
var SENTINEL = "1 1"; // <---- String!
var SENTINEL = -1; // <---- Number!
So you should consider something like this instead (renamed accordingly):
var printRolls = function(text) { println(text); return text; }
var rolls = printRolls(rollOne + " " + rollTwo);
if(rolls == SENTINEL) {
println("You did it");
}
Or to simplify it a bit:
if(printRolls(rollOne + " " + rollTwo) == SENTINEL)
println("You did it");
It is possible that println doesn't return the string that is passed into. In that case, you can use
if (SENTINEL === rollOne + " " + rollTwo)
to format the string and properly test equality.
In JavaScript it is possible to assign the return value from any function to a variable similar to how you've done it:
var anyVariable = anyFunction();
But, some functions return the value undefined. Or they return a number, or an array, or...whatever.
I imagine your println() function prints the value you pass to it somewhere (on the screen? to the console?) and then returns undefined. Or if it is returning the printed value it is in a format different to what you have used in your SENTINEL variable. So then when you try to compare that with SENTINEL it won't be equal.
To fix your original function, assign the sum of the rolls to a variable, then print and test that:
function start() {
var SENTINEL = 2;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = rollOne + rollTwo;
println(num);
if(num == SENTINEL) {
println("You did it");
}
}
EDIT: if you want the println() to display a string like "1 1" or "3 5" to show what each of the two rolls were then do this:
println(rollOne + " " + rollTwo);
That is, create a new string that is the result of concatenating rollOne's value with a single space and then rollTwo's value.

variable string appearing as undefined, new string not appearing in array, javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Categories