So what if I made immutable. You can only set once and unpack to a function that can name the values. I could also drop the valueOf usage.
Does that sound saner? It is definitely simpler and a lot closer to an actual tuple implementation.
I want to turn this into a small repository so maybe I will take the little good bits and drop anything unnecessary.
Re:Tuples in JavaScript
by nwhitehead on Monday July 29, 2013 @03:08PM
(#6123167)
Actually thinking about it more you might want to have "Tuple" and "MutableTuple" objects. In languages that use parentheses notation for tuples you need to decide which one you want, but since you have names you can have both just with different names.
An alternative would be the old lambda-calculus trick of just saving the function with values in the closure.
function Tuple(/* args... */) {
var args = arguments;
this.unpack = function(fn) {
return fn.apply(null, args);
}
}The problem with that being that you redefine the unpack function every time a tuple is created. The this._NAME = VALUE; may look awful but it's more efficient.
You are just relying on your users to not abuse _ prefixed variables. It's far from ideal.
Actually, good js implementations (like v8, for example) will only create one code object shared by all the unpack functions, with separate closures assigned to each. And since closures can (usually) be statically determined, they can use an offset lookup for the closured variable in place of a hashtable. So it's not quite as inefficient as it looks :).
Huh, I never knew that. Thanks! As long as you're in a decent environment that kind of definition becomes a lot smoother. I like it.
Streamlined, removed the insanity, tested and documented. Any better? https://github.com/Wolfy87/tuple
I absolutely hate the idea of "valueOf". Why would you ever in your life want to add together tuple values by default? It's a misfeature that is begging to cause bugs. A better feature would be some way of applying functions across tuples of the same size (map and fold type operations) to make it easy to build up correct comparison functions.