понедельник, 17 октября 2011 г.

Simple objects dynamic constructors (Array \ Arguments ⇒ Object)

In the previous article I described function that gives you function overloading ability in JavaScript. But in the end it become a bit Javash. Anyway Than I needed to created some other object with different keys, like:
{a1:1, a2:2, a3:3}
{alpha:10, beta:20, gamma:30}
So I made this:
function dynConstructor(){
  var varNames = Array.prototype.slice.call(arguments);
  return function(){
    var values = Array.prototype.slice.call(arguments);
    if(Array.isArray(values[0])){
      values = values[0];
    }
    var map = {};
    varNames.slice(0, values.length).forEach(function(varName, i){
      map[varName] = values[i];
    });
    return map;
  }
}
This function makes other functions given list of keys, which will be merged with values, than you put into obtained function as parameters. It's more clear with examples:
var pointVector = dynConstructor('x', 'y', 'z');
var displaceVector = dynConstructor('a1', 'a2', 'a3');
var anglesVector = dynConstructor('a', 'b', 'c');

pointVector(10, 20, 30) == {x:10, y:20, z:30};
displaceVector(1, 2, 3) == {a1:1, a2:2, a3:3};
anglesVector(120, 90, 90) == {a:120, b:90, c:90};

pointVector([1, 2, 3]) == {x:1, y:2, z:3}; //You can pass an array also
Also you can use it for creating any simple constructors. Like:
var person = dynConstructor('Name', 'Age', 'Sex');

person('Aleksandr', 27, 'M') == {Name: 'Aleksandr', Age: 27, Sex: 'M'};
Btw, do you know that you can use UTF-8 symbols related to specific domain for variable? =) Like this:
var displaceVector = dynConstructor('a¹', 'a²', 'a³');
var anglesVector = dynConstructor('ɑ', 'β', 'ɣ');

displaceVector(1,2,3) == {'a¹':1, 'a²':2, 'a³':3};
anglesVector(120, 90, 90) == {ɑ:120, β:90, ɣ:90};

Комментариев нет:

Отправить комментарий