forked from BigAB/jQuery-Combinations-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.combinations.1.0.js
45 lines (40 loc) · 1.28 KB
/
jquery.combinations.1.0.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* jQuery combinations - v1.0 - 29/10/2011
* http://github.com/bigab/jquery/jquery-combinations-plugin/
*
* Copyright (c) 2011 "BigAB" Adam Barrett
* licensed under the MIT license.
* http://bigab.mit-license.org
* @author BigAB - Adam Barrett
*/
(function($) {
$.combinations = function(arrayOfArrays) {
if (Object.prototype.toString.call(arrayOfArrays) !== '[object Array]') {
throw new Error("combinations method was passed a non-array argument");
}
var combinations = [],
comboKeys = [],
numOfCombos = arrayOfArrays.length ? 1 : 0,
arrayOfArraysLength = arrayOfArrays.length;
for(var n = 0; n < arrayOfArraysLength; ++n) {
if(Object.prototype.toString.call(arrayOfArrays[n]) !== '[object Array]') {
throw new Error("combinations method was passed a non-array argument");
}
numOfCombos = numOfCombos*arrayOfArrays[n].length;
}
for(var x = 0; x < numOfCombos; ++x) {
var carry = x,
comboKeys = [],
combo = [];
for(var i = 0; i < arrayOfArraysLength; ++i) {
comboKeys[i] = carry % arrayOfArrays[i].length;
carry = Math.floor(carry / arrayOfArrays[i].length);
}
for(var i = 0; i < comboKeys.length; ++i) {
combo.push(arrayOfArrays[i][comboKeys[i]]);
}
combinations.push(combo);
}
return combinations;
}
})(jQuery);