|
let initText = "Thanks!"; |
|
|
|
let whichConvert = 0, // ['ASCII (char)', 'ASCII (int)', '8-bit (Byte)'] |
|
count = 0, |
|
nIntervId; |
|
|
|
window.onload = autoChange(); |
|
|
|
function autoChange() { |
|
convert0101(); // Execute it initially, then `setTimer` will take over. |
|
nIntervId = setInterval(convert0101, 3000); |
|
} |
|
|
|
function stopAutoConvert() { |
|
// Clear the setInterval and show/hide the appropriate inline messages. |
|
clearInterval(nIntervId); |
|
document.getElementById('convert0000').style.display = 'none'; |
|
document.getElementById('convert1111').style.display = 'inline'; |
|
} |
|
|
|
function convert0101() { |
|
if (count == 5) { // Let it go 2 times around. |
|
stopAutoConvert(); |
|
} |
|
count++; // Count will simply forever increase (but never again hit 5). |
|
|
|
if (whichConvert == 0) { |
|
|
|
// If whichConvert is 0; Set text as initial text |
|
// And move `whichConvert` to 1 (for ASCII (int)) |
|
|
|
document.getElementById("convert0101").innerText = initText; |
|
whichConvert = 1; |
|
|
|
} else { |
|
|
|
// If whichConvert is 1 || 2 then |
|
// use either ASCII (int) || 8-bit conversion methods |
|
|
|
const newText = initText |
|
.split("") |
|
.reduce( (word, ltr, idx) => { |
|
if (whichConvert == 1) { |
|
|
|
/* Convert to ASCII */ |
|
word[idx] = '' + ltr.charCodeAt().toString() + '_'; |
|
} else { |
|
|
|
/* Convert to 1-Byte bits */ |
|
word[idx] = '' + ("000000000" + ltr.charCodeAt().toString(2)).substr(-8) + '_'; |
|
} |
|
return word; |
|
}, []).join().replace(/,/g, ''); |
|
document.getElementById("convert0101").innerText = newText.substr(0, newText.length-1); |
|
|
|
// If whichConvert is currently 1 (ASCII (int)), |
|
// then set to 2; Else reset back to 0 |
|
whichConvert = whichConvert == 1 ? 2 : 0; |
|
} |
|
} |
|
|
|
function updateIt(newVal) { |
|
stopAutoConvert(); |
|
initText = newVal; |
|
whichConvert = 0; |
|
convert0101(); |
|
} |
|
|
|
function byteString(dec) { |
|
// `byteString()` attribution: [Ray Toal](https://stackoverflow.com/a/24337276/638153) |
|
// Although now used inline (due to limited sample), this SO answer was quite helpful. |
|
if (dec < 0 || dec > 255 || dec % 1 !== 0) { |
|
throw new Error(dec + " does not fit in a byte"); |
|
} |
|
return ("000000000" + dec.toString(2)).substr(-8) |
|
} |
|
|
|
/* Additional Inspiration: |
|
https://www.google.com/search?q=javascript+mdn+int+char |
|
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt |
|
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a |
|
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval |
|
*/ |