Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a truth table enumerating all possible parameter combinations for a function taking booleans. Arguments: target function, number of boolean arguments, string for true, string for false.
function truthTable(fun, bits, t, f){
var vars = bits || 4
, max = 1 << vars
, tStr = t || ' T '
, fStr = f || ' F '
, i, j, str, arr, set, res;
for (i = 0; i < max; i++) {
str = '';
arr = [];
for (j = vars - 1; j >= 0; j--) {
set = ((i & (1 << j)) != 0);
arr.push(set);
str += set ? tStr : fStr;
}
res = fun.apply(null, arr);
console.log(str + ' => ' + (res ? tStr : fStr) + ' [' + i + ']');
}
}
@arnehormann
Copy link
Author

arnehormann commented Mar 14, 2013

This is a short one-line form (e.g. for pasting in node):
var tt = function(fun,bits,t,f){var vars=bits||4,max=1<<vars,tStr=t||' T ',fStr=f||' F ',i,j,str,arr,set,res;for(i=0;i<max;i++){str='';arr=[];for(j=vars-1;j>=0;j--){set=((i&(1<<j))!=0);arr.push(set);str+=set?tStr:fStr}res=fun.apply(null,arr);console.log(str+' => '+(res?tStr:fStr)+' ['+i+']')}};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment