Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active September 27, 2016 12:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/e26f2339b705cff557e6 to your computer and use it in GitHub Desktop.
Save branneman/e26f2339b705cff557e6 to your computer and use it in GitHub Desktop.
Pairs (length 2 tuples) in JavaScript
/**
* Pair
* @todo Implement algebraic structures: Setoid, Functor
*/
var Pair = function(fst, snd) {
if (this instanceof Pair) {
if (Array.isArray(fst) && fst.length === 2 && typeof snd == 'undefined') {
this[0] = fst[0];
this[1] = fst[1];
} else {
this[0] = fst;
this[1] = snd;
}
this.length = 2;
} else {
return new Pair(fst, snd);
}
};
Pair.prototype.fst = function() {
return this[0];
};
Pair.prototype.snd = function() {
return this[1];
};
Pair.of = Pair.prototype.of = function(a1, a2) {
return new Pair(a1, a2);
};
/**
* Create fst() and snd() functions
*/
var fst = function(pair) {
if (pair instanceof Pair) {
return pair.fst();
} else if (Array.isArray(pair) && pair.length === 2) {
return pair[0];
}
throw 'Not a pair: ' + pair;
};
var snd = function(pair) {
if (pair instanceof Pair) {
return pair.snd();
} else if (Array.isArray(pair) && pair.length === 2) {
return pair[1];
}
throw 'Not a pair: ' + pair;
};
/**
* Example usage 1: Given an array of length 2
*/
var pair1 = Pair(['one', 2]);
fst(pair1); //=> 'one'
snd(pair1); //=> 2
/**
* Example usage 2: Given 2 arguments
*/
var pair2 = Pair('one', 2);
fst(pair2); //=> 'one'
snd(pair2); //=> 2
/**
* Example usage 3: Given an array, using Ramda
*/
var text = ['one', 'two', 'three'], numbers = [1, 2, 3];
var list = R.zip(text, numbers);
R.map(snd, list); //=> [1, 2, 3]
/**
* Example usage 4: Creating pairs with Pair.of(), using Ramda
*/
var text = ['one', 'two', 'three'], numbers = [1, 2, 3];
var list = R.zip(text, numbers);
R.map(Pair.of, list); //=> [Pair, Pair, Pair]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment