Skip to content

Instantly share code, notes, and snippets.

@thephilip
Created March 17, 2017 21:26
Show Gist options
  • Select an option

  • Save thephilip/45883539162ed1a874e54ab41475e0f3 to your computer and use it in GitHub Desktop.

Select an option

Save thephilip/45883539162ed1a874e54ab41475e0f3 to your computer and use it in GitHub Desktop.
JavaScript Tuple Implementation
/*
* Tuple.js - JavaScript Tuple Implmentation
* ------------------------------------------------
* The Tuple object is an immutable, fixed-length
* structure used to hold a heterogeneous set of n
* typed values that can be used for inter-function
* communication. For instance, you can use it to
* build quick value objects.
*
* Borrowed from 'Functional Programming in Javascript'.
*
*/
const Tuple = function( /* Types */ ) {
// Reads provided argument types the tuple will contain.
const typeInfo = Array.prototype.slice.call(arguments, 0);
/*
Declares an internal type _T in charge of making sure
the types match the corresponding values.
*/
const _T = function( /* Values */ ) {
// Extracts values to be stored in the tuple.
const values = Array.prototype.slice.call(arguments, 0);
// Check for non-null values.
if(values.some((val) => val === null || val === undefined)) {
throw new ReferenceError('Tuples may not have any null values');
}
/*
Check that the tuple has the correct arity with
respect to the number of types defined.
*/
if(values.length !== typeInfo.length) {
throw new TypeError('Tuple arity does not match its prototype');
}
/*
Check that each value passed in matches the correct type in
the tuple definition using the checkType function. Every
tuple element will translate to a roperty of the tuple
referred to by ._n, where n is the index of the element
(starting at 1).
*/
values.map(function(val, index) {
this['_' + (index + 1)] = checkType(typeInfo[index])(val);
}, this);
Object.freeze(this);
};
/*
Extracts all the values from the tuple as an array. You can use
this with ES6 assignment destructuring to map tuple values into
variables.
*/
_T.prototype.values = function() {
return Object.keys(this).map(function(k) {
return this[k];
}, this);
};
return _T;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment