Last active
November 12, 2017 12:29
-
-
Save jtulach/7337484 to your computer and use it in GitHub Desktop.
Compute Factorial in a Web Page
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
package dew.demo.factorial; | |
import java.math.BigInteger; | |
import net.java.html.json.*; | |
@Model(targetId="", className="UI", properties={ | |
/** n is the number we want to compute factorial | |
* when the Compute! button is pressed | |
*/ | |
@Property(name="n", type=int.class), | |
/** array of computed results */ | |
@Property(name="results", type=String.class, array=true) | |
}) | |
class ComputeFactorial { | |
/** The actual method to compute factorial. | |
* Shows we can use {@link BigInteger} in the | |
* browser to get better numbers than JavaScript | |
* offers by default. | |
*/ | |
public static String factorial(int n) { | |
BigInteger r = BigInteger.valueOf(1); | |
for (int i = 1; i <= n; i++) { | |
r = r.multiply(BigInteger.valueOf(i)); | |
} | |
return r.toString(); | |
} | |
/** Called when a button Compute! is pressed. | |
* Compute the result and add it to the result list. | |
*/ | |
@Function static void compute(UI ui) { | |
ui.getResults().add( | |
ui.getN() + "! = " + factorial(ui.getN()) | |
); | |
ui.setN(ui.getN() + 1); | |
} | |
// initialize the UI | |
public static void main(String... args) { | |
new UI().applyBindings(); | |
} | |
} |
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
Factorial for: <input data-bind="value: n"></input> | |
<button data-bind="click: compute" type="number">Compute!</button> | |
<h3>Your Results</h3> | |
<ul data-bind="foreach: results"> | |
<li data-bind="text:$data"></li> | |
</ul> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One can see the code in action at http://dew.apidesign.org/dew/#7337484