Need help to understand Vue.js function [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment to make calculator using vue.js.
Much of it works, I'm confused about how to implement the '=' function.
I found this piece of code in an article that does something similar but I don't understand what it does. Can someone explain it?
https://scotch.io/tutorials/build-a-scientific-calculator-with-vuejs
I found this Piece of code:
if ((app.current).indexOf("^") > -1) {
var base = (app.current).slice(0, (app.current).indexOf("^"));
var exponent = (app.current).slice((app.current).indexOf("^") + 1);
app.current = eval("Math.pow(" + base + "," + exponent + ")");
} else {
app.current =app.current
}
Can someone please explain what the above function does, line-by-line?

// checks if app.current have '^' by getting the index
// if the method indexOf doesn't find anything it return -1
if (app.current.indexOf('^') > -1) {
// gets the first element till the index where it found '^'
var base = app.current.slice(0, app.current.indexOf('^'));
// gets the number after the 'ˆ'
var exponent = app.current.slice(app.current.indexOf('^') + 1);
// eval is evil
// it gets the string and transfoms into valid code
// wich means to do the operation
app.current = eval('Math.pow(' + base + ',' + exponent + ')');
} else {
// if it doesn't find the index it keeps the same value
app.current = app.current;
}
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Related

I am missing something [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've looked this code over and over.. I typed it as I was learning from lesson material, and have checked and checked over and over again. the code works for the instructor, but not me. Is it my mistake or is it a problem for the platform I am using? It not working may seems trivial comparing to needing to understand what is being taught, but I still would like to understand all that I can. thank you. https://codepen.io/Slimmwillis/pen/EQWpGP?editors=1111
function yearsUntilRetirement(name, year) {
var age = calculateAge(year);
var retirement = 65 - age;
if (retirement >= 0) {
console.log(name + ' retires in ' + retirement + ' years.');
} else {
console.log(name + ' is already retired.');
}
}
yearsUntilRetirment('John', 1990);
you need to be very careful while typing. You're not calling the right function so nothing happens.
function yearsUntilRetirement(name, year) {
var age = calculateAge(year);
console.log('hello');
var retirement = 65 - age;
if (retirement >= 0) {
console.log(name + " retires in " + retirement + " years.");
} else {
console.log(name + " is already retired.");
}
}
yearsUntilRetirment("John", 1990);
Check the yearsUntilRetirment("John", 1990); ! the name doesn't match the function.

Missing ; before statement in Google Script [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
It says I have a Missing ; before statement on the "var api =..." line.
I'm not sure what else it is I need to do.
If you need to see the rest of the script, please let me know. I will gladly submit everything else.
function askWolframAlpha_(q, app) {
try {
var api = "http://api.wolframalpha.com/v2/query?podindex=2&format=plaintext&appid=" + 67ULAK-L9R928PL76 + "&input=" + encodeURIComponent(q);
var response = UrlFetchApp.fetch(api, {
muteHttpException: true
});
// Parse the XML response
if (response.getResponseCode() == 200) {
var document = XmlService.parse(response.getContentText());
var root = document.getRootElement();
if (root.getAttribute("success").getValue() === "true") {
return root.getChild("pod").getChild("subpod").getChild("plaintext").getText();
}
}
} catch (f) {}
return false;
}
The problem is the 67ULAK-L9R928PL76 in the following line:
var api = "http://api.wolframalpha.com/v2/query?podindex=2&format=plaintext&appid=" + 67ULAK-L9R928PL76 + "&input=" + encodeURIComponent(q);
Change to:
var api = "http://api.wolframalpha.com/v2/query?podindex=2&format=plaintext&appid=67ULAK-L9R928PL76&input=" + encodeURIComponent(q);
or at least to:
var api = "http://api.wolframalpha.com/v2/query?podindex=2&format=plaintext&appid=" + "67ULAK-L9R928PL76" + "&input=" + encodeURIComponent(q);

JavaScript prototypes - technical interview [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I had a JavaScript interview last wednesday, and I had trouble with one of the questions. Maybe you guys can give me hand with it?
The question was: how would you go about this printing var a and s to the console, in camel case, with the help of a prototype function...
var s = “hello javier”;
var a = “something else”;
String.prototype.toCamelCase = function() {
/* code */
return capitalize(this);
};
...so the result is the same as doing this?
console.log(s.toCamelCase());
console.log(a.toCamelCase());
>HelloJavier
>SomethingElse
Thanks!
var s = 'hello javier';
var a = 'something else';
String.prototype.toCamelCase = function() {
return capitalize(this);
};
function capitalize(string) {
return string.split(' ').map(function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}).join('');
}
console.log(a.toCamelCase());
console.log(s.toCamelCase());
Reference
How do I make the first letter of a string uppercase in JavaScript?
I would go with something like this:
var s = "hello javier";
var a = "something else";
String.prototype.toCamelCase = function() {
function capitalize(str){
var strSplit = str.split(' ');
// starting the loop at 1 because we don't want
// to capitalize the first letter
for (var i = 1; i < strSplit.length; i+=1){
var item = strSplit[i];
// we take the substring beginning at character 0 (the first one)
// and having a length of one (so JUST the first one)
// and we set that to uppercase.
// Then we concatenate (add on) the substring beginning at
// character 1 (the second character). We don't give it a length
// so we get the rest.
var capitalized = item.substr(0,1).toUpperCase() + item.substr(1);
// then we set the value back into the array.
strSplit[i] = capitalized;
}
return strSplit.join('');
}
return capitalize(this);
};
// added for testing output
console.log(s.toCamelCase());
console.log(a.toCamelCase());

How to extract a number from a two line string in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to extract the number "40" from following two lines:
Total Boys:4 (40 min)
Main Students:0 (0 min)
How can I do that using javascript? Thank in advance!
Or without a regex
str.split('min').shift().split('(').pop().trim();
FIDDLE
Simply use a regular expression:
var str = 'Total Boys:4 (40 min)\nMain Students: 0 (0 min)';
var number = str.match(/\((\d+)/)[1]; // 40
Here's a simple regex to pull that value out:
var str = 'Total Boys:4 (40 min)\nMain Students:0 (0 min)';
var regexp = /.*\((\d+) min\)\n.*/;
var matches = regexp.exec(str);
alert('match: ' + matches[1]);
Another way of doing it would be simply str.match(/\d+/g)[1] using regex.
DEMO
suppose you have your string inside str andyou want to store the number inside n
another approach is this:
var index1,
index2,
index3,
n;
index1 = str.indexOf('Total Boys:', 0);
index2 = str.indexOf('(', index1) + 1;
index3 = str.indexOf(' ', index2);
n = str.substring(index2, index3);
note that this approach will get only the min value of "Total Boys", not "Main Students".
It will work even if you have another similar line before "Total Boys"

Variable.match for amount > 999.99 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
For example :
Var1 = 289.56
I use this formula :
foundStr = Var1.match("[0-9]+\.[0-9]+");
Price( parseFloat(foundStr).toFixed(2) );
But when Var1 > 999.99 (Example : 2,356.21)
What is the script find the string ?
foundStr = Var1.match(??);
Thank you
You already have a numeric variable, why are you messing with strings?
var number1 = 289.56;
if (number1 > 999.99) {
// do whatever
}
If you're trying to round, use Math.floor instead:
var number1 = 289.56485345734593453;
var roundedNumber1 = Math.floor(number1 * 10) / 10; // two decimal points
I think you just want to remove the commas and check if its a float, but its hard to tell based off your question. How about something like this:
var Var1 = "1,234.567";
var parsed = parseFloat(Var1.replace(",",""), 10);
if (isNaN(parsed)) {
// its not a valid number, so deal with it as needed
}
else {
// parsed now holds your Number, so use it
}
This approach will work regardless of if the number is >= 1000.
var Var1 = "2,356.21";
foundStr = String(Var1.match(/([0-9]{1,3},)?[0-9]{0,3}\.[0-9]+/g)).replace(/,/g, "");
var result = parseFloat(foundStr).toFixed(2);

Categories

Resources