The base class definition
For starters, I needed a simple class definition that created the tuple instance, set it’s size and stored some initial data.
1 2 3
new Tuple(...) you can now define a tuple that creates an internal storage array of the appropriate length. Now we need a function that sets those values, that function also needs to be called from the constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Now the arguments you pass to the constructor are sliced into an array and pushed onto the
pack method which bundles them into the storage array. The pack method simply iterates over it’s arguments and assigns each one to it’s place in the storage.
Getting the data out
It’s all well and good dumping values into a fixed size tuple, but how do you get them out? Better still, how do you get them out in a Haskell-ish way the will allow you to assign each value to a variable of your choice?
1 2 3
When you call unpack all of the values in the storage array are passed to your callback function for you to do with as you please. That means you can assign each value to any name you want;
z for example. This is inspired by pattern matching a tuple in Haskell and unpacking the values into variables of your choosing.
So with the current code, you could do something like this.
1 2 3 4 5 6 7
This creates a tuple that contains three numbers: A width, height and depth of a box. We can then use
unpack to assign each value to a variable, do some stuff with them and return their result. You could recreate Haskell’s
snd functions fairly easily with similar code.
1 2 3 4 5 6 7 8 9 10 11
I would not advise using anonymous functions like I have done above in production. Please place them into stand alone functions that are not declared every time. I have only written them like that for brevity.
Integration with other tuples and types
One thing you can add to make it behave slightly more like a native type is to add a
1 2 3
You can take this a little further by adding a
valueOf method that will even allow you to concatenate or add together multiple tuples, albeit in a rudimentary way.
1 2 3 4 5 6 7 8 9 10 11 12
Now with a
valueOf method you can do stuff like this…
1 2 3 4 5
So now you can create a tuple type which sits in between an object and an array which has some pretty cool arithmetic and concatenation methods due to
You can play about with my code in this fiddle.
Due to a sudden influx of views and opinions, I have decided to create an actual project based off of this idea; albeit a very simplified one. It can be found in the repository, Wolfy87/tuple. I have finished and published the first release tonight and you can grab it from GitHub, Bower (
bower install tuple) and npm (
npm install tuple-w, the name “tuple” was taken).
You will notice that this solidified version is a lot simpler though. There is no
valueOf and there is no