John Smith
John Smith

Reputation: 6269

Dynamic exports

Let's say I have an array with different options:

exports.options =  [
   ["big_house",   { width: 260 , length: 140 }],
   ["small_house", { width: 36  , length: 90 }]
    ...
 ];

How can I dynamically create, for each option an export function? (They should for example look like these ones):

exports.big_house = function(extra_width, extra_length){
  build(260, 140, extra_width, extra_length); 
};

exports.small_house = function(extra_width, extra_length){
  build(36, 90, extra_width, extra_length); 
};

My tries started with: this.options.forEach(function(option){.. but to get the String to transform to a function name that accepts two arguments, I'm constantly failing.

Thanks!

Upvotes: 1

Views: 1491

Answers (2)

jfriend00
jfriend00

Reputation: 708056

You can expose an object for each separate key and one of the items in the object can be a function:

exports.options =  {
    big_house: { width: 260, length: 140, build: function(extra_width, extra_length) {
        return build(this.width, this.length, extra_width, extra_length);
    }},
    small_house: { width: 36, length: 90, build: function(extra_width, extra_length) {
        return build(this.width, this.length, extra_width, extra_length);
    }},
}

Then, when you use it, you could do this:

var items = require('builder');
items.big_house.build(10, 20);

In fact, in the implementation, you can even use a common function:

function _build(extra_width, extra_length) {
    return build(this.width, this.length, extra_width, extra_length);
}

exports.options =  {
    big_house: {width: 260, length: 140, build: _build},
    small_house: {width: 36, length: 90, build: _build},
}

To get a list of the options, you can use Object.keys():

var b = require('builder');
var items = Object.keys(b.options);

Of you could make a specific method to retrieve the list of items.

Upvotes: 1

mscdex
mscdex

Reputation: 106736

You can reference functions by a variable containing its name using the bracket syntax. For example:

exports.options.forEach(function(v) {
  var fnName = v[0];
  var width = v[1].width;
  var length = v[1].length;
  exports[fnName] = function(extra_width, extra_length) {
    build(width, length, extra_width, extra_length);
  };
});

Upvotes: 2

Related Questions