Get result of last statement in JavaScript Code - javascript

Given is a file with JavaScript-Code. For example:
1 + 1;
3 + 3;
I want to receive the value of the last expression (which is 6 in this case).
This could be achieved via
node --print "1 + 1; 3 + 3;"
But I cannot pass the code as a string because the code can contain quotes which conflict with the quotes around the code (e.g. node -p "1 + 1; aFunction("string")").
Unfortunately, node's --print parameter cannot deal with files.
Another approach would be to modify the source file. I could use the eval-Function which has the desired behaviour that eval("1 + 1; 3 + 3") returns 6. Unfortunately, I run into the same conflicts with the quotes.
I hope I could make my point clear. I'm looking forward to your answers.

If you're on Linux and maybe MacOS and maybe maybe Windows/Cygwin you can put the code in a file and then try this:
node -p < thefile.js

Related

Updated post: How do I get a JavaScript factorial programs' loop to show the working used? See requirements

this is my second post today as the original wasn’t clear and I was urged to repost because despite getting some good answers they did not fit the requirements of the code. I have been challenged to write a program in JavaScript that allows the user to perform several tasks, one of which is to ask the user for a number and calculate the factorial of that number and then display it in the format listed in the requirements. As I do not know much about Java script I used already asked questions and managed to get the calculation to work but could not figure out how to get the required output whilst still meeting the requirements.
Requirements:
• Can only use the provided variables Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation). This is a limitation set by the challenge and not me
• Cannot use fancy libraries
• Need to use a loop solution for the output. The answers on the other post required introducing new variables, perhaps it is my lack of understanding but perhaps the poorly written pseudo code I have obtained since the last post may help.
• Be output in the format: (it is an alert so that part of the program is fine)
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Poorly written pseudo code:
Code:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions, including my first post which this one now succeeds as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but do not know where to begin implementing that and I'm only allowed to use that solution.
Again, I would like to apologise for my first post, the given answers would work great if not for the incredibly ridiculous restrictions set by the challenge provider, who is also responsible for giving me rubbish pseudo code, which isn't what I'm going for but I am using to consider the loop.
I appreciate the time it takes to read this amd provide solutions so I will go back and try and mark all working answers in the last post for any normal problems people might search for answers for.
This is a bit of a dirty hack but it should satisfy the condition that no other variables than number, count, and factorial are used.
let number = 5;
let factorial = 120;
// ^ Do your own calculation for this
alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)
So what is going on here?
We use an interpolated template string to produce the desired output, expressions inside ${these things} are evaluated as strings. And what is the mess we put in there?
Array.from(Array(number + 1).keys())
The expression above creates the array [0,1,2,3,4,5].
.slice(1) gives us [1,2,3,4,5]
.reverse() gives us [5,4,3,2,1]
join("*") gives us "5*4*3*2*1"
Which when all put together gives us The factorial of 5 is 5*4*3*2*1=120
And voila! The output is printed in the desired format without introducing any new variables.
Edit: Oh and you do not need to use an interpolated string for this. You may as well concatenate regular strings together as you have done in your question. e.g.
"The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial

Javascript string.length does not equal Python len()

Imagine the following text entered in an HTML textarea:
123456
7
If one calculates the length of this text via javascript, i.e. string.length, that comes out to 10.
Now if that input's length is measured in python, i.e. via len(string), it is 13.
It does not look 13 to the human eye, but if one runs print repr(string) in python, we get 123456\r\n\r\n\r\n7. That is 13 characters, not 10. For reference, this test was carried out in Ubuntu OS.
Is there any way for python to report the string length via a mechanism that imitates javascript's string.length's result? I.e. in simpler terms, how do I get 10 in python?
I understand I can manually iterate and collapse \r\n into a single character, but I wonder if there is a more robust - even inbuilt - way to do it? In any case, an illustrative example would be great!
You can make use of Regular Expressions which is much more elegant than iterating. Replacing the characters \n and \r by '' does the trick.
Use the re module of python.
import re
x = '123456\r\n\r\n\r\n7'
y = re.sub(r'\r\n','\n',x)
print(len(y)) #Answer will be 10
For further reference, check out the python docs

creating large files with node.js

Hello I have a question with node.js mainly with creating new larger files.
I understand how to do stuff such as
fs.writeFile('ss.js', 'console.log("hello")');
But my problem comes when I need to create a file that has 5 or more lines, AKA all the files. I'm not sure where to even start on this problem. I've been through a lot of tutorials and all of them jusy say, "Now create a file and fill it with these lines of code.", but none of them actually go indepth into how to create a file with multiple lines of code.
Greatly appreciated if anyone can go over this basic step. Thanks!
You're kind of undermining "large files". Those are simply line-breaks, which is (at least on Unix) around 5 extra bytes (since linebreaks are represented as a single byte).
Take this example:
fs.writeFile("test.js", "var test = 'ey b0ss';\nconsole.log(test);\nif (true) {\nconsole.log('yey');\n}");
In this example, line-breaks are represented as \n, considering you're on a Unix machine, this would work fine (If you're on a Windows machine, I think \r is the alternative)... (You can use the \r\n combo to represent a line-break on both OS's.)
The output of this on a Unix machine is:
var test = 'ey b0ss';
console.log(test);
if (true) {
console.log('yey');
}
When actually creating large files (in terms of storage), in my opinion, it'd be best to represent it as a buffer.
For instance, say we wanted to create a file that had 100,000 "a" characters in it.
var largeBuffer = new Buffer(""), i,
anotherBuffer = new Buffer("a"),
fs = require("fs");
for (i=0; i<=100000; i++) {
largeBuffer = Buffer.concat([largeBuffer, anotherBuffer]);
}
fs.writeFile("a.txt", largeBuffer);

Confusing JavaScript statement about string Concatenation

I was developing a node.js site and I made a copy and paste error that resulted in the following line (simplified for this question):
var x = "hi" + + "mom"
It doesn't crash and x = NaN. Now that i have fixed this bug, I am curious what is going on here, since if I remove the space between the + signs I get an error (SyntaxError: invalid increment operand)
My Question is : Can some explain to me what is going on in the statement and how nothing (a space between the + signs) changes this from an error to a NaN?
PS. I am not sure if this should go here or programers.stackoverflow.com. Let me know if I posted on the wrong site.
It's being interpreted like this:
var x = "hi" + (+"mom")
The prefix + tries to coerce the string to a number. Number('mom') is NaN, so +'mom' is also NaN.

Running an equation from a string

I am trying to create a simple online calculator that can run basic calculations in JavaScript.
I have managed to create the interface so that numbers and operators and stored in a form field.
What I would like to be able to do is pass the values within the form field to a function that will calculate the total of the form field.
The form field could contain anything from a simple "10 + 10" to more complex equations using brackets. The operators in use are +, -, *, and /.
Is it possible to pass the form field's text (a string) to a JavaScript function that can recognize the operators and the perform the function of the operation on the values?
A possible value in the text field would be:
120/4+130/5
The function should then return 56 as the answer. I have done this in JavaScript when I know the values like this:
function WorkThisOut(a,b,c,d) {
var total = a/b+c/d;
alert (total);
}
WorkThisOut(120,4,130,5);
What I would like to be able to do is pass the full value "120/4+130/5" to the function and it be able to extract the numbers and operators to create the total.
Does anyone have any ideas on how this could be done or if it is even possible? this may get more complex where I may need to pass values in parentheses "(120/4)+(130/5)"
I may get blasted for this. But, here it goes anyway.
There are three solutions I can think of for this:
Implement your own parser, lexer and parse out the code.
That's not super easy, but it may be a great learning experience.
Run an eval under a subdomain meant only for that, so that scripts can't maliciously access your site
Sanitize the input to contain only 12345678790+-/*().
eval(input.replace(/[^0-9\(\)\+\-\*\/\.]/g, ""));
Please blast away with tricks to get around this solution
You can use the expression parser included with the math.js library:
http://mathjs.org
Example usage:
math.eval('1.2 / (2.3 + 0.7)'); // 0.4
math.eval('5.08 cm in inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
It is pretty hard to do much damage with eval if you don't allow identifiers.
function reval(string){
var answer='';
if(/^[\d()\/*.+-]+$/.test(str)){
try{
answer= eval(str);
}
catch(er){
answer= er.name+', '+er.message;
}
}
return answer;
}
what about eval?
consider calc as the id of textfield. then
$('#calc').change(function(e){
alert(eval($(this).val()));
})
but remember to validate input before processing.
This is a pretty old topic, but for the new visitors who have similar problem: the string-math package calculates the [String] equations like in the sample above 120/4+130/5. It also recognizes parentheses.

Categories

Resources