Skip to content

Commit ab883c0

Browse files
committed
implement tool
1 parent b539fbc commit ab883c0

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

index.html

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<!DOCTYPE html>
2+
<meta charset="utf-8">
3+
4+
<body>
5+
<div>
6+
<p>
7+
A simple online tool for converting between decimal numbers and their <a
8+
href="https://en.wikipedia.org/wiki/Fibonacci_coding">Fibonacci coding</a>.
9+
</p>
10+
<br>
11+
<div>
12+
Input:
13+
<input type="text" id="input" size="50">
14+
<button id="d2f">Decimal to Fibonacci</button>
15+
<button id="f2d">Fibonacci to Decimal</button>
16+
</div>
17+
<br>
18+
<div>
19+
Output:
20+
<input type="text" id="output" size="50">
21+
</div>
22+
</div>
23+
<script src="./script.js"></script>
24+
</body>

script.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
const d2f = num => {
2+
const helper = (f1, f2, n) => {
3+
if (f2 > n) {
4+
return [n, "1"];
5+
}
6+
[rem, b] = helper(f2, f1 + f2, n);
7+
if (rem >= f2) {
8+
return [rem - f2, "1" + b];
9+
} else {
10+
return [rem, "0" + b];
11+
}
12+
}
13+
if (num <= 0) {
14+
return "Number must be greater than 0";
15+
}
16+
return helper(1, 1, num)[1];
17+
};
18+
19+
const f2d = b => {
20+
const helper = (f1, f2, i) => {
21+
if (i >= b.length - 1) {
22+
return 0;
23+
}
24+
const char = b.charAt(i);
25+
if (char == '1') {
26+
return f2 + helper(f2, f1 + f2, i + 1);
27+
} else if (char == '0') {
28+
return helper(f2, f1 + f2, i + 1);
29+
}
30+
}
31+
for (var i = 0; i < b.length; i++) {
32+
switch (b.charAt(i)) {
33+
case '1':
34+
case '0':
35+
break;
36+
default:
37+
return `Invalid character at position ${i}: ${b.charAt(i)}`;
38+
}
39+
}
40+
if (b.length < 2 || b.charAt(b.length - 1) != '1' || b.charAt(b.length - 2) != '1') {
41+
return "Last two bits must be 1";
42+
}
43+
return helper(1, 1, 0);
44+
};
45+
46+
document.getElementById("d2f").addEventListener("click", () => {
47+
const input = document.getElementById("input").value;
48+
const output = d2f(parseInt(input));
49+
document.getElementById("output").value = output;
50+
});
51+
document.getElementById("f2d").addEventListener("click", () => {
52+
const input = document.getElementById("input").value;
53+
const output = f2d(input);
54+
document.getElementById("output").value = output.toString();
55+
});

0 commit comments

Comments
 (0)