How do I convert Dynamic Javascript to Text? - javascript

I have some code (whatever is inside the body of the jsToBeConverted function below) that I want to be able to convert it into text so that the user can copy it and then paste it inside a <script> element on their site in order to have it executed.
someElement.onclick = function ()
{
var textForUserToCopy = (function ()
{
x = document.getElementById('someInput').value;
var jsToBeConverted = function ()
{
var y = x + 6;
var z = function (a)
{
return (a + 5);
};
window.d = z(y);
};
var jsToExecute = "(" + jsToBeConverted + ")();"
return jsToExecute;
})();
};
However this would generate the following text :
"(function ()
{
var y = x + 6;
var z = function (a)
{
return (a + 5);
};
window.d = z(y);
})();"
But this isn't what I want. If the above is evaluated x will obviously be undefined.
What I want is for x to be replaced by its value at the time and then have the js converted into text. So if the value of x happened to be 123, this is what the generated text should look like :
"(function ()
{
var y = 6 + 6;
var z = function (a)
{
return (a + 5);
};
window.d = z(y);
})();"
If the above string is evaluated - window.d would be 17
Is the there some standard function/process for generating/converting dynamic code into text?
Thank you

You can simply concatenate.
e.g.:
"function (x) { return " + generated_value + " + x }";
For a more elegant looking solution, see string formatting:
JavaScript equivalent to printf/string.format

Related

Closures: Scope Chain Variables - Not sure how variables link up

Really new to Javascript. This code is taken from MDN.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sum(1);
var s1 = s(2);
var s2 = s1(3);
var s3 = s2(4);
console.log(s3) //log 20
When I try to input different variable names (EX below) they don't seem to work and I don't understand how everything links up together to spit out the answer 20.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var w = sum(1);
var x = s(2);
var y = s1(3);
var z = s2(4);
console.log(s3) //log 20
When I change it to this it also does not work. The console tells me that sa is not defined
// global scope
var e = 10;
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sm(1);
var s1 = sa(2);
var s2 = sb(3);
var s3 = sc(4);
console.log(sc) //log 20
I can keep throwing out more examples that don't work. Someone, please help me understand how the first example works.
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
The function sm is taking one argument and is returning a function which takes one argument. The function sm returns is not named sb. Try to think of it as the return value of sm .
So, when you do
var s = sm(1);
The returned function is stored in the variable s
Now if you want to run the second function (sa inside sm) you need to invoke s.
var s1 = s(2);
The returned function (sb) is stored inside varibale s1.
Similarly,
var s2 = s1(3);
var s3 = s2(4);
console.log(s3); // 20

Replace a variable in a function with the value in javascript

I am looking for a way to replace a variable in a function with its actual value. I am going to convert this function into a string and send via a HTTP request and thus need to convert the variables inside the function with their values.
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
// Send funcString as a parameter
For eg. in the above code if I send funcString as it is, whoever receiving it will have no idea what is the value of x.
Since I am ultimately sending a string I would like to send
"function () {let y = 0.53 + 10; return y;}" (assuming
Math.random() produced 0.53 at runtime).
Is there any way to do this?
I am doing this in a nodejs project so a npm module would be fine by me too.
Well if you are returning this function as a string, just use String#replace() method to replace x occurrence with its value.
This is how you should use it:
funcString.replace('x', x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
console.log(funcString.replace('x', x));
Edit:
If your variable has many occurrences and can be part of other variables just use a regex with replace method.
funcString.replace(/\bx\b/g, x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
let fix ='true';
let z = x * 2;
return y;
}.toString();
console.log(funcString.replace(/\bx\b/g, x));
use replace with regex, g will search all x-es
let x = Math.random();
let funcString = function () {
let y = x + 10;
let a = x + 10;
let b = x + 10;
return y;
}.toString().replace(/x/g, x);
console.log(funcString);

I have created a webpage that will factorialize a number. I have created that function. Now I need to create a function that will show my math.

Can anyone help me to do this? The function is empty below and I am unsure how to proceed. I have the factorized number showing on the webpage now I would like the math to show before it. Something like this;
A user inputs: 3
Our site outputs: "1 x 2 x 3 = 6"
function factorialize(num) {
var total = 1;
if (num > 1) {
for (var i = 1; i <= num; i += 1) {
total *= i;
}
}
return total;
}
function showMath() {
};
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var result = factorialize(userInput);
var myWork = showMath(userInput);
// var
$("#output").text(myWork + " = " + result);
});
});
You should build up an array of all the factors. Then it is easy to reduce() the array to a single value or join() it into a string.
function toFactorialArray(num){
var n = num,
arr = [n];
while (--n) arr.push(n);
return arr;
}
function getResult(arr){
return arr.reduce(
function( memo, current ) {
return memo * current
}, 1
);
}
function getWork(arr){
return arr.reverse().join(' * ');
}
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var factors = toFactorialArray(userInput);
var result = getResult(factors);
var myWork = getWork(factors);
$("#output").text(myWork + " = " + result);
});
});

Variable hoisting examples [duplicate]

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 7 years ago.
Hi I have a snippet of code. I am confused about change of value x1 when I remove non-related part of same code. I searched about it and I came to know that it has to do with hoisting. But the value x1 is still unclear even with hoisting concept for me. Can someone please make me clear on this?
var x = 10;
function main() {
document.write("<br>x1 is " + x);
x = 20;
if (x > 0) {
var x = 30;
document.write("<br>x2 is " + x);
}
var x = 40;
var f = function(x) {
document.write("<br>x3 is " + x);
}
f(50);
}
main();
The output of this code is:
x1 is undefined
x2 is 30
x3 is 50
If I change this code to:
var x = 10;
function main() {
document.write("<br>x1 is " + x);
}
main();
The output is:
x1 is 10
So what is happening here is a common pitfall.
The simplest way to put this is. When you set var x = 30 inside your main function, you are actually redefining the scope that var x = 10 had for use inside this function. This has to do with how Javascript executes and scope.
By defining x inside the function, your scope for x has changed. Below is an example of what I mean and a version of your code that works
Example:
var test = 'test';
function run(){
console.log(test);
var test=1;
}
Your Code Updated:
var x = 10;
function main() {
console.log("<br>x1 is " + x);
x = 20;
if (x > 0) {
x = 30;
console.log("<br>x2 is " + x);
}
x = 40;
var f = function(x) { console.log("<br>x3 is " + x); }
f(50);
}
main();
Good question btw.
Since this is somewhat of a very interesting scope of how Javascript executes, consider the following code and its outputs to get the full idea
var test = 'test';
function run(){
console.log(test);
test=1;
console.log(test);
var test=2;
console.log(test);
}
console.log(test);
run();
console.log(test);
Very interesting to see how this reacts.
All variable and function declarations get "hoisted" or moved to the top of their scope. The undefined value for x is caused because the var x statement gets moved up to the top of main however the assignment = 30 does not.
So, your code will read more like this:
var x = 10; // x is 10
function main() {
var x; // x declaration is "hoisted"
document.write("<br>x1 is" + x); // x1 is undefined
x = 20; // x is 20
if (x > 0) {
x = 30; // x is 30
document.write("<br>x2 is" + x);// x2 is 30
}
x = 40; // x is 40
var f = function(x) { // x is 50
document.write("<br>x3 is" + x);// x3 is 50
}
f(50);
}
main();
You can read more about Hoisting here: JavaScript Scoping and Hoisting

can a function reference itself in javascript?

Suppose we define a function that simply increments its input by some stored value dd:
var obj={}
obj.dd=1
obj.f=function(x){
return x+this.dd
}
Alternatively you could create a closure for dd as follows but this would create a static increment as opposed to one that could be altered later:
var dd=1
var f=function(x){
return x+dd
}
We could alternatively store dd in the function itself:
var obj={}
obj.f=function(x){
return x+this.f.dd
}
obj.f.dd=1
I am curious as to whether it is possible for a function to retrieve a variable attached to itself without going through a parent object, something like a self keyword that would refer to the function itself and would allow the following:
var f=function(x){
return x+self.dd
}
f.dd=1
I know it is unnecessary to do such a thing but I think it would be cool if you could.
You can give function literals a name:
var f = function me(x) {
return x + me.dd;
};
f.dd = 1;
This doesn’t work properly in older versions of IE/JScript, though, as me and f don’t reference the same object. The (deprecated and not usable in strict mode) alternative is arguments.callee:
var f = function(x) {
return x + arguments.callee.dd;
};
f.dd = 1;
Also, your note about the closure isn’t quite right; it can be altered later, even through another function:
var dd = 1;
var f = function(x) {
return x + dd;
};
var setdd = function(_dd) {
dd = _dd;
};
A function is an object. If you reference the var holding the function:
var f = function (x) {
return x + f.dd
};
f.dd = 1;
alert(f(1));
result: 2
If the function is named, you can do the same:
function foo(x) {
return x + foo.dd;
}
foo.dd = 1;
alert(foo(1));
result: 2

Categories