开发者

dynamic function arguments in array

开发者 https://www.devze.com 2023-04-03 13:25 出处:网络
A bit hard to find a proper title... I have an object which basically is a wrapper around an array of Cartesian coordinates (x, y values). I\'m now defining a few transform methods on that array (mov

A bit hard to find a proper title...

I have an object which basically is a wrapper around an array of Cartesian coordinates (x, y values). I'm now defining a few transform methods on that array (move, rotate, skew, mirror). Basically all these methods need an iterator of the array, so I wrote a function iterate:

myList.prototype.iterate = function() {
    var fn = arguments[0];  // first argument is the actual transform function.
    ..

Optionally a second argument may be passed in, which must be an instance of myList. If this argument is passed in, the function operates on a clone of the argument, otherwise it must operate on itself:

    if (arguments.length === 2 and arguments[2].type === this.type) {
        target = $.extend({}, arguments[2]); // deep copy.
    } else {
        target = this;
    }

So 开发者_开发技巧far so good, now I'm defining my transformation functions (rotate)

myList.prototype.rotate=function() {
    var rotatePoint = function (angle, pt) {
    return {x : (pt.x * Math.cos(angle) - pt.y* Math.sin(angle))
        , y : (pt.x * Math.sin(angle) + pt.y* Math.cos(angle)) };
    }
    if (arguments.length() === 1)  {    //Alternative for this if statement.
        return this.iterate(rotatePoint.curry(arguments[0]));
    } else {
        return this.iterate(rotatePoint.curry(arguments[0]),arguments[1]);
    }
}

curry is a non standard javascript function, and is described here. I'm not so glad with the if statement. I think it can be done more elegant with apply or call. But I haven't been able to figure this out. Problem is also that arguments[2] in iterate will be an empty array, screwing my if statement when comparing types.

How can rewrite the if statement in some nice clean javascript code, so that there is no second argument at all when it is not in passed in iterate;


does something like this work?

var args = $.makeArray(arguments),
    iterator = rotatePoint.curry(args.shift());
args.unshift(iterator);
return this.iterate.apply(YOURTHIS, args);
0

精彩评论

暂无评论...
验证码 换一张
取 消