[javascript] JavaScript variable assignments from tuples

You can have a tuple type in Javascript as well. Just define it with higher order functions (the academic term is Church encoding):

_x000D_
_x000D_
const Tuple = (...args) => {_x000D_
  const Tuple = f => f(...args);_x000D_
  return Object.freeze(Object.assign(Tuple, args));_x000D_
};_x000D_
_x000D_
const get1 = tx => tx((x, y) => x);_x000D_
_x000D_
const get2 = tx => tx((x, y) => y);_x000D_
_x000D_
const bimap = f => g => tx => tx((x, y) => Tuple(f(x), g(y)));_x000D_
_x000D_
const toArray = tx => tx((...args) => args);_x000D_
_x000D_
// aux functions_x000D_
_x000D_
const inc = x => x + 1;_x000D_
const toUpperCase = x => x.toUpperCase();_x000D_
_x000D_
// mock data_x000D_
_x000D_
const pair = Tuple(1, "a");_x000D_
_x000D_
// application_x000D_
_x000D_
console.assert(get1(pair) === 1);_x000D_
console.assert(get2(pair) === "a");_x000D_
_x000D_
const {0:x, 1:y} = pair;_x000D_
console.log(x, y); // 1 a_x000D_
_x000D_
console.log(toArray(bimap(inc) (toUpperCase) (pair))); // [2, "A"]_x000D_
_x000D_
const map = new Map([Tuple(1, "a"), Tuple(2, "b")]);_x000D_
console.log(map.get(1), map.get(2)); // a b
_x000D_
_x000D_
_x000D_

Please note that Tuple isn't used as a normal constructor. The solution doesn't rely on the prototype system at all, but solely on higher order functions.

What are the advantages of tuples over Arrays used like tuples? Church encoded tuples are immutable by design and thus prevent side effects caused by mutations. This helps to build more robust applications. Additionally, it is easier to reason about code that distinguishes between Arrays as a collection type (e.g. [a]) and tuples as related data of various types (e.g. (a, b)).