Luckyy
Luckyy

Reputation: 1031

Javascript: making functions at runtime

update

solution works in foreach loop but not in for loop

function x(number){
  return number - 10;
}
var i = 0
var runtimefunctions = {};
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
 for (var key in allLevels) {
   runtimefunctions[i] = function() { return x(i); };
i++;
};

console.log(runtimefunctions[1]()); // -6
console.log(runtimefunctions[2]()); // -6
console.log(runtimefunctions[3]()); // -6

tried hard to make functions but it's first time to create such thing so cant understand the proper way...

I have a function..

function x(number){
return number - 10;
}
runtimefunctions = {};
now I have a loop to run
[1,2,3].forEach(function(y){
   //here I want to create a function.. which will make a function x(y) -- like this
   runtimefunctions[x] = new Function("return function x_" + levelIterator + "(levelIterator){ console.log(levelIterator); x(" + y + ") }")();

});

so basically..want to make functions like this.

runtimefunctions= {
 "1": x(1),
 "2": x(2),
and so on
}

Upvotes: 0

Views: 68

Answers (3)

dhilt
dhilt

Reputation: 20744

Is this what you need?

function x(number){
  return number - 10;
}

var runtimefunctions = {};

[1,2,3].forEach(function(y){
   runtimefunctions[y] = function() { return x(y); };
});

console.log(runtimefunctions[1]()); // -9
console.log(runtimefunctions[2]()); // -8
console.log(runtimefunctions[3]()); // -7

To satisfy your next (for-in) requirement, you need to closure the index variable with additional function call:

var runtimefunctions = {}, i = 0;
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
  runtimefunctions[i] = function(index){ return function() { return x(index); } }(i++);
};

Upvotes: 6

TryingToImprove
TryingToImprove

Reputation: 7407

You could do something like this

// Found in your code
var x = (a) => {
    console.log(a)
};    

var runtimefunctions = {};

[1, 2, 3].forEach(function(y) {
    //Create a function with a parameter named "levelIterator"
    runtimefunctions[y] = Function("levelIterator", "{ console.log(levelIterator); x(" + y + ") }");

});

runtimefunctions[1]('test')

Upvotes: 0

karina
karina

Reputation: 829

It is much easier. For example:

const createFunctionWith = (x) => {
    return (param) => console.log(x, param)
}
let a = [1,2,3].map(x => createFunctionWith(x));
console.log(a[1]("bebe")); // 2, "bebe"

https://jsfiddle.net/muLxoxLd/

Upvotes: 0

Related Questions