1.0.4 • Published 7 years ago

tristate-logic v1.0.4

Weekly downloads
20
License
SEE LICENSE IN LI...
Repository
github
Last release
7 years ago

Software Plumbers Tristate Logic

Library for working with tri-state (true/false/null) logic in javascript

Rationale

Tri-state logic is occasionally more useful than strict boolean logic, as it handles the real world case where the truth of some propositions is unknown. Most SQL databases in fact implement a form of tri-state logic. For example, the WHERE clause a = b OR c = d will return results if a is null so long as c = d, because 'UKNOWN or TRUE' is deemed TRUE.

Truth tables for classic tri-state logic are below:

Truth Table for AND(a,b)

abAND
TRUETRUETRUE
TRUEFALSEFALSE
FALSETRUEFALSE
FALSEFALSEFALSE
UNKNOWNFALSEFALSE
UNKNOWNTRUEUNKNOWN
FALSEUNKNOWNFALSE
TRUEUNKNOWNUNKNOWN
UNKNOWNUNKNOWNUNKNOWN

Truth Table for OR(a,b)

abOR
TRUETRUETRUE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
UNKNOWNFALSEUNKNOWN
UNKNOWNTRUETRUE
FALSEUNKNOWNUNKNOWN
TRUEUNKNOWNTRUE
UNKNOWNUNKNOWNUNKNOWN

If we map 'UKNOWN' to 'null' in javascript, the behaviour of the standard operators is frustratingly close to the above:

Comparison of Tristate AND(a,b) with a && b

aba && bAND
falsefalsefalsefalse
falsetruefalsefalse
truefalsefalsefalse
truetruetruetrue
nulltruenullnull
nullfalsenullfalse
truenullnullnull
falsenullfalsefalse
nullnullnullnull

Comparison of Tristate OR(a,b) with a || b

abjs orOR
falsefalsefalsefalse
falsetruetruetrue
truefalsetruetrue
truetruetruetrue
nulltruetruetrue
nullfalsefalsenull
truenulltruetrue
falsenullnullnull
nullnullnullnull

The exceptions (in italics) unfortunately break some important cases; for if we want to iterate over a collection until some condition is definitely false, being unable to reliably destinguish between 'unknown' and 'false' is a problem.

Example

let result1 = and(null, false)
let result2 = or(null, false)

and result1 should equal false while result2 equals null. In other cases and(a,b) === a && b.

These simple binary and and or functions have to do some extra checks and comparisons in order to work. Some additional API is defined, which can be (very, very, slightly) more efficient and more explicit.

let a = FALSE;
let b = TRUE;
let c = UNKNOWN;

if (a.and(c) === FALSE) console.log('hello'); 

will log 'hello'.

For the latest API documentation see The Software Plumbers Site

Project Status

Beta. It seems functional, and the unit tests pass.