Last active
August 29, 2015 14:12
-
-
Save balanza/9cf72e9dffc79e350da2 to your computer and use it in GitHub Desktop.
A simple javascript function that implements truth tables, useful for handling multiple conditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var TruthTable = require('truthtable'); | |
var condition1 = true; | |
var condition2 = false; | |
var tt = new TruthTable(condition1, condition2) | |
.on('01', function() { | |
console.log('01'); | |
}) | |
.on('11', function() { | |
console.log('11'); | |
}) | |
.on('10', function() { | |
console.log('10'); | |
}) | |
.on('1*', function() { | |
console.log('1*'); | |
}) | |
.on('*1', function() { | |
console.log('*1'); | |
}).go(); | |
//output: | |
// 10 | |
// 1* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var TruthTable = function() { | |
this.conds = Array.prototype.slice.call(arguments); | |
this.actions = {}; | |
}; | |
TruthTable.prototype.on = function(cond, fn) { | |
if (cond.length != this.conds.length) { | |
throw "condition length must match"; | |
} | |
this.actions[cond] = fn; | |
return this; | |
}; | |
TruthTable.prototype.go = function() { | |
var actions = this.actions; | |
var conds = this.conds; | |
for (var cond in actions) { | |
if (actions.hasOwnProperty(cond)) { | |
var c = cond.split(''); | |
var match = true; | |
for (var i = 0; i < c.length; i++) { | |
var cond_i = c[i]; | |
if ((cond_i == '*') || (cond_i == '1' && conds[i]) || (cond_i == '0' && !conds[i])) { | |
// console.log('good'); | |
} else { | |
match = false; | |
break; | |
} | |
} | |
if (match) { | |
var action = actions[cond]; | |
if (action) action(); | |
} | |
} | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment