Skip to content

Instantly share code, notes, and snippets.

@jtulach
Last active November 12, 2017 12:29
Show Gist options
  • Save jtulach/7337484 to your computer and use it in GitHub Desktop.
Save jtulach/7337484 to your computer and use it in GitHub Desktop.
Compute Factorial in a Web Page
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();
}
}
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>
@jtulach
Copy link
Author

jtulach commented Nov 6, 2013

One can see the code in action at http://dew.apidesign.org/dew/#7337484

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment