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.
Related
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}];
I've been watching a javascript tutorial to refresh my knowledge of it.
I just need some guidance on why he decided to use this code "style"
Basically, there's a variable named result with an empty string ("") and I'm not so sure why he used (result += ...) when he can also use (result = ...) where it showed the same output when I tried.
function mySentence(myName, myVerb){
var result = "";
result += myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
vs
function mySentence(myName, myVerb){
var result = "";
result = myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
Link of video: https://youtu.be/PkZNo7MFNFg
36:28:00 : Word Blanks
The only reason I can think of for having it there is that the author wanted to be able to rearrange a series of statements after the initial declaration that all used += without having to worry about which was the first statement originally. E.g.:
var result = "";
result += "something";
result += "another thing";
result += "yet another thing";
...where they may want later to swap things around:
var result = "";
result += "another thing";
result += "something";
result += "yet another thing";
The variable result is set to "", an empty string in the beginning.
When you do result= the variable will be replaced with the new value.
But when you do result+= the variable does not get replaced. It will be added with the value that already exists.
For example, in your code, if the variable is set to some value in the beginning, like result="The answer is: ", then the two styles would yield different results. The result= style will return Dale walked towards the tree.. And the result+= will return The answer is: Dale walked towards the tree.
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
I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});
I recently created a function in javascript that takes in a file name and a max character limit where the result needs to follow these rules:
Always include file extension
If shrinking occurs, leave the first part and last part of the file name intact.
Always replace the removed characters with '...'
If file length is under the max then do nothing
You can assume the max is a least 5 chars long
Now I've already solved this, but it got me thinking if there is a more elegant or simple way to do this in javascript using regular expressions or some other technique. It also gave me an opportunity to try out jsFiddle. So with that in mind here is my function:
function ReduceFileName(name, max){
if(name.length > max){
var end = name.substring(name.lastIndexOf('.'));
var begin = name.substring(0, name.lastIndexOf('.'));
max = max - end.length - 3;
begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
return begin + end;
}
return name;
}
And here it is on js Fiddle with tests
I'm not sure that regular expressions will be necessarily more elegant, but so far I came up with the following which passes your tests:
function ReduceFileName(name, max){
if(name.length > max) {
var ell ="\u2026"; // defines replacement characters
var ext = (/\.[^\.]*$/.exec(name) || [""])[0]; // gets extension (with dot) or "" if no dot
var m = (max-ell.length-ext.length)/2; // splits the remaining # of characters
var a = Math.ceil(m);
var z = Math.floor(m);
var regex = new RegExp("^(.{"+a+"}).*(.{"+z+"})"+ext, "");
var ret = regex.exec(name);
return ret[1]+ell+ret[2]+ext;
}
return name;
}
Since I didn't get much activity on this, I'm assuming there isn't a much better way to do this, so I'll consider my method as the answer until someone else comes up with something else.
function ReduceFileName(name, max){
if(name.length > max){
var end = name.substring(name.lastIndexOf('.'));
var begin = name.substring(0, name.lastIndexOf('.'));
max = max - end.length - 3;
begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
return begin + end;
}
return name;
}