liveBook · Manning

Tuple

As explained in Functional Programming in JavaScript

A finite ordered collection of fixed length that groups multiple values into a single composite value.

A tuple is a finite, ordered group of values treated as one entity. It is useful when a function needs to return related results, such as a success status and an error message, without adding multiple arguments. section 4.2

Returning validation results

A validation function can return a tuple such as (false, 'Input is too long!'). In JavaScript, the same idea can use a custom Tuple type: `const Status = Tuple(Boolean, String);` and return `new Status(false, 'Invalid input!')`. The tuple keeps the values ordered, immutable, and available as one result. section 4.2

Listing 4.2. Typed Tuple data type
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;
};

Inspect the typed JavaScript Tuple implementation, including arity checks, null-value rejection, type checks, and freezing. section 4.2

How Functional Programming in JavaScript covers it

How deep it goes
Defines tuples, demonstrates returned values, and implements typed immutable tuples with arity and value checks.
Examples
Uses validation status and error messages, typed status tuples, triangle-angle values, and string pairs.
What you can do after
Build typed immutable tuples in JavaScript and use them to return and pass related values as one result.
How it connects
Connects tuples with function arity, pure functions, referential transparency, type compatibility, and function pipelines.

Also explained in

Compare how 15 books explain tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.