cardiograph-computer/logging.js

83 lines
2.7 KiB
JavaScript

/**
* Display a table of memory locations.
* Call with [start] and [end] indices to display a range.
* @param {Uint8Array} mem - Memory to display
* @param {number} [start] - A start-index, in decimal
* @param {number} [end] - An end-index, in decimal
**/
const logMemory = (mem, start=0, end=mem.length) => {
// This function can only handle
// an even number of array entries
if ((start % 2) === 1) { start -= 1; }
if ((end % 2) === 1) { end += 1; }
mem = mem.slice(start, end);
console.log(`┌────────┬────────┬─────────┐`);
console.log(`│ addr │ opcode │ operand │`);
console.log(`├────────┼────────┼─────────┤`);
//for (let i = 0; i < mem.length; i += 2) {
for (let i = start; i < mem.length; i +=2) {
console.log(`${num2hex(i)}${num2hex(mem[i])}${num2hex(mem[i+1])}`);
// Add a blank row every 4 lines:
if (((i + 2) % 8) === 0) {
if ((i < (mem.length - 2))) {
console.log(`│ │ │ │`);
}
}
}
console.log(`└────────┴────────┴─────────┘`);
}
const logRunningHeader = () => {
console.log();
let time = new Date();
console.log( `┌─────────────────────┐`);
console.log( `│ Running at ${time.toLocaleTimeString('en-GB')}` );
console.log( `└─────────────────────┘`);
}
/**
* @param {number} num
* @returns {string}
*/
const num2hex = (num) => num.toString(16).toUpperCase().padStart(2, "0");
/**
* @param {string} hex
* @returns {number}
*/
const hex2num = (hex) => parseInt(hex, 16);
/**
* Convert a number to binary, padded to 8 bits
* See here for an explanation: https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript
* @param {number} num
* @returns {string} binary representation of the input
**/
const num2bin = (num) => (num >>> 0).toString(2).padStart(8, "0");
/**
* Convert a number to binary, padded to 4 bits
* See here for an explanation: https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript
* @param {number} num
* @returns {string} binary representation of the input
**/
const num2bin_4bit = (num) => (num >>> 0).toString(2).padStart(4, "0");
/**
* @param {string} bin
* @returns {number}
*/
const bin2num = (bin) => parseInt(bin, 2)
module.exports = {
"logMemory": logMemory,
"logRunningHeader": logRunningHeader,
"num2hex": num2hex,
"hex2num": hex2num,
"num2bin": num2bin,
"num2bin_4bit": num2bin_4bit,
"bin2num": bin2num,
}