Search code examples
javascriptlinear-programming

How can I use the jsLPSolver library locally in a browser?


I would like to use the jsLPSolver library locally in a browser, not via Node.js, for running linear programming optimisations.

Following the 'Install' section of the README, I'm loading the solver.js script from unpkg.com.

I tried the exact example in the "Use" section of the README, but get the error Uncaught ReferenceError: require is not defined. It looks like the require.js library might offer a workaround for that, for those not using Node.js. But then I found JWally's example here, that does not use require(). However when I run that in the script shown below, I get the error Uncaught ReferenceError: Solver is not defined in my console.

How can I resolve this so that I can run jsLPSolver in a browser? Feels like I may be missing something fundamental, that's not specific to jsLPSolver.

<script src="https://unpkg.com/javascript-lp-solver/prod/solver.js"></script>
<script>
var solver = new Solver,
    results,
    model = {
    optimize: "profit",
    opType: "max",
    constraints: {
        "Costa Rican" : {max: 200},
        "Etheopian": {max: 330}
    },
    variables: {
        "Yusip": {"Costa Rican" : 0.5, "Etheopian": 0.5, profit: 3.5},
        "Exotic": {"Costa Rican" : 0.25, "Etheopian": 0.75, profit: 4}
    }
};

results = solver.solve(model);
console.log(results);
</script>


Solution

  • <script src="https://unpkg.com/javascript-lp-solver/prod/solver.js"></script>
    <script>
      const model = {
        optimize: "profit",
        opType: "max",
        constraints: {
          "Costa Rican": {
            max: 200
          },
          Etheopian: {
            max: 330
          },
        },
        variables: {
          Yusip: {
            "Costa Rican": 0.5,
            Etheopian: 0.5,
            profit: 3.5
          },
          Exotic: {
            "Costa Rican": 0.25,
            Etheopian: 0.75,
            profit: 4
          },
        },
      };
    
      // We don't need to declare 'solver', it is already exported via the script we load
      const results = solver.Solve(model); // Note the capital '.Solve'
      console.log("Results", results);
    </script>


    Please try this. I believe your confusion comes from the documentation which uses an example interpreted via Node. You don't need to declare a solver variable, it is exported for you already via the imported script.