Tuple in JavaScript
Overview
In JavaScript, a tuple is an immutable structure that groups together items of different types, allowing them to be passed as a single entity between functions. This is particularly useful for managing function arity by returning multiple values as one, thus avoiding the need for ad hoc types or heterogeneous arrays. Tuples are fixed-length and can hold a heterogeneous set of typed values, making them ideal for inter-function communication.
Implementing Tuples
JavaScript provides all the necessary tools to implement your own version of a Tuple. Below is an example of a typed tuple data type:
[Listing 4.2. Typed Tuple data type](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-4/70)
const Tuple = function( /* types */ ) {
const typeInfo = Array.prototype.slice.call(arguments, 0); #1
const _T = function( /* values */ ) { #2
const values = Array.prototype.slice.call(arguments, 0); #3
if(values.some((val) => #4
val === null || val === undefined)) {
throw new ReferenceError('Tuples may not have
any null values');
}
if(values.length !== typeInfo.length) { #5
throw new TypeError('Tuple arity does not
match its prototype');
}
values.map(function(val, index) { #6
this['_' + (index + 1)] = checkType(typeInfo[index])(val);
}, this);
Object.freeze(this); #7
};
_T.prototype.values = function() { #8
return Object.keys(this).map(function(k) {
return this[k];
}, this);
};
return _T;
};
#1 - Reads the provided argument types the tuple will contain
#2 - Declares an internal type _T in charge of making sure the types match the corresponding values
#3 - Extracts the values to be stored in the tuple
#4 - Checks for non-null values. Functional data types shouldn’t permit null values to permeate.
#5 - Checks that the tuple has the correct arity with respect to the number of types defined
#6 - Checks that each value passed in matches the correct type in the tuple definition using the checkType function (shown later). Every tuple element will translate to a property of the tuple referred to by ._n, where n is the index of the element (starting at 1).
#7 - Makes the tuple instance immutable
#8 - Extracts all values from the tuple as an array. You can use this with ES6 assignment destructuring to map tuple values into variables.
Usage of Tuples
Status Example
The Tuple object can be used to create quick value objects, such as Status:
const Status = Tuple(Boolean, String);
This allows for the creation of a Status object that holds a Boolean and a String, which can be used, for example, in a student SSN validation function:
[Listing 4.3. Using tuples for the isValid function](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-4/70)
// trim :: String -> String
const trim = (str) => str.replace(/^\s*|\s*$/g, '');
// normalize :: String -> String
const normalize = (str) => str.replace(/\-/g, '');
// isValid :: String -> Status
const isValid = function (str) {
if(str.length === 0){
return new Status(false, #1
'Invald input. Expected non-empty value!');
}
else {
return new Status(true, 'Success!');
}
}
isValid(normalize(trim('444-44-4444'))); //-> (true, 'Success!')
#1 - Declares a Status type that holds values for status (Boolean) and message (String)
StringPair Example
The occurrence of 2-tuples is so frequent in software that it’s worth making them first-class objects. When combined with JavaScript ES6 support for destructured assignment, you can map tuple values to variables in a clean manner:
[Listing 4.4. StringPair type](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-4/70)
const StringPair = Tuple(String, String);
const name = new StringPair('Barkley', 'Rosser');
[first, last] = name.values();
first; //-> 'Barkley'
last; //-> 'Rosser'
const fullname = new StringPair('J', 'Barkley', 'Rosser'); #1
#1 - Throws an arity mismatch error
In this example, StringPair is a tuple that holds two strings. Attempting to create a StringPair with more than two values results in an arity mismatch error, demonstrating the fixed-length nature of tuples.
Conclusion
Tuples in JavaScript provide a robust way to handle multiple values of different types as a single entity, ensuring type safety and immutability. They are particularly useful in functional programming paradigms for reducing function arity and improving code modularity and reusability.
FAQ (Frequently asked questions)
What are tuples in functional programming?
How do tuples help manage function arity?
What is the purpose of the Tuple function in JavaScript?
How does the Tuple function ensure immutability?
What happens if a tuple contains null values?
How does the Tuple function check for correct arity?
How are tuple values accessed in the Tuple function?