Add a simple Fibonacci example to demonstrate three little modules

This commit is contained in:
Tissevert 2020-01-01 17:13:43 +01:00
parent 7cf2f84dae
commit e84024b605
5 changed files with 98 additions and 0 deletions

12
demo/index.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>SJW demo</title>
<script src="main.js"></script>
</head>
<body>
<h1>Fibonacci calculator</h1>
<p>The <input type="text" value="5" id="n"/>th number in Fibonacci's sequence is <span id="result">8</span></p>
</body>
</html>

47
demo/main.js Normal file
View File

@ -0,0 +1,47 @@
window.addEventListener('load', function() {
var modules = {};
modules['Memoizator'] = (function(modules) {
return {
memoize: memoize
};
function memoize(f) {
var cache = {};
return function(n) {
if(cache[n] == undefined) {
cache[n] = f(n);
}
return cache[n];
};
}
})();
modules['Math.Fibonacci'] = (function(memoize, modules) {
var get = memoize(function(n) {
if(n < 2) {
return 1;
} else {
return get(n-1) + get(n-2);
}
});
return {
get: get
};
})(modules['Memoizator'].memoize);
(function(nth, modules) {
var input = document.getElementById('n');
var latestKnownValidInput = input.value;
var result = document.getElementById('result');
input.addEventListener('change', function() {
var newValue = input.value;
if(isNaN(newValue) || newValue < 0 || newValue.trim().length == 0) {
input.value = latestKnownValidInput;
}
result.textContent = nth(input.value);
});
})(modules['Math.Fibonacci'].get);
});

13
demo/src/Main.js Normal file
View File

@ -0,0 +1,13 @@
import get as nth from Math.Fibonacci;
var input = document.getElementById('n');
var latestKnownValidInput = input.value;
var result = document.getElementById('result');
input.addEventListener('change', function() {
var newValue = input.value;
if(isNaN(newValue) || newValue < 0 || newValue.trim().length == 0) {
input.value = latestKnownValidInput;
}
result.textContent = nth(input.value);
});

View File

@ -0,0 +1,13 @@
import memoize from Memoizator;
var get = memoize(function(n) {
if(n < 2) {
return 1;
} else {
return get(n-1) + get(n-2);
}
});
return {
get: get
};

13
demo/src/Memoizator.js Normal file
View File

@ -0,0 +1,13 @@
return {
memoize: memoize
};
function memoize(f) {
var cache = {};
return function(n) {
if(cache[n] == undefined) {
cache[n] = f(n);
}
return cache[n];
};
}