3 ms·
I like the "unpack" idea of using a function to name the parts of the tuple, it's elegant and fits well into JavaScript. I'm a bit less sure about exposing the
by nwhitehead 13y ago
I like the "unpack" idea of using a function to name the parts of the tuple, it's elegant and fits well into JavaScript. I'm a bit less sure about exposing the "pack" method outside the constructor. That makes tuples mutable, which isn't what I normally want. Normally I want immutable collections of possibly mutable objects for my tuples. If I wanted a mutable collection I would use an array.
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.
- Olical 13y agoSo 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.
- nwhitehead 13y agoActually 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.
- jayferd 13y agoAn 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); } }
- Olical 13y agoThe 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.
- jayferd 13y agoActually, 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 :).
- Olical 13y agoHuh, 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.
- Olical 13y agoStreamlined, removed the insanity, tested and documented. Any better? https://github.com/Wolfy87/tuple https://github.com/Wolfy87/tuple