Skip to content

Instantly share code, notes, and snippets.

@arnehormann
Created March 14, 2013 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnehormann/5162314 to your computer and use it in GitHub Desktop.
Save arnehormann/5162314 to your computer and use it in GitHub Desktop.
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

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