Constrained
JavaScript Constraint solver with automatic variable assignment and event emission on variable change.
Finds a feasible solution to a system of constraints and assign it to linked object properties. Based on cassowary.js, an implementation of the simplex algorithm (it can only handle linear continuous optimisation problems).
How to use
In a browser
Include Constrained's build in your html using either the minified library or the unminified version.
In Node.js
Install Constrained using npm install constrained
, then require it:
var Constrained = ;
API
The following example shows how to instantiate and solve a system with two variables, one constant and one constraint:
var myObject1 = a: 0 b: 0 ;var myObject2 = c: 100 ;// Instantiation of the systemvar mySystem = ;// Instantiation of the variables and the constantmySystem; // variable named xmySystem; // variable named ymySystem; // constant named c// Definition of the systemmySystem;// Solving the system to obtain a feasible solutionmySystem;// Displaying the resultmySystem; // x + y = 100// Making sure that objects have been updatedconsole;
To change a constant's value:
// Changing the value of the property associated with cmyObject2c = 25;// Solving the system to obtain a new feasible solution// that respect the new constant parametermySystem;// Displaying the solutionmySystem; // x + y = 25// Making sure that objects have been updatedconsole;
To specify an objective to optimize:
// Bounding xmySystemmySystem;// Solving the system will now give an optimal// solution to the optimization problemmySystem;// Displaying the solutionmySystem; // x + y = 25, x minimized and >= 0// Making sure that objects have been updatedconsole;
Possibility to chain function calls:
var mySystem =;mySystem;// Fetching variable valuesvar x1 = mySystem;var x2 = mySystem;var x3 = mySystem;var z = mySystem;console;
Possibility to define a system using the function API (for improved performance):
var Cst = Constrained;var myObject1 = x: 0 ;var myObject2 = x: 0 ;var myObject3 = x: 0 ;var mySystem = ;var myVariable1 = mySystem;var myVariable2 = mySystem;var myVariable3 = mySystem;var objective = Cst;var myConstraint1 = Cst;var myConstraint2 = Cst;var myConstraint3 = Cst;var myConstraint4 = Cst;var myConstraint5 = Cst;var myConstraint6 = Cst;mySystem;mySystem;
To add callbacks on variable or solution changes:
var mySquare = width: 0 height: 0 area: 0 ;var myPerimeter = length: 10 ;// Instantiation of the systemvar mySystem =;mySystem;mySystem;mySystem;// Solving the system to obtain a feasible solutionmySystem;// Changing the value of the perimetermyPerimeterlength = 20;// Solving the system to obtain a new feasible solution// that respect the new constant parametermySystem;
Note: Do not hesitate to post issues to suggest improvements