上下文:
我写了一小段代码以可视化一些二进制数字。这是一个自包含的HTML文件,应该可以在浏览器中使用。
输出:
问题:
.input-block
div)?
.container {
display: flex;
flex-flow: row wrap;
justify-content: flex-start;
align-items: flex-start;
height: 80vh;
}
.block {
padding: 15px;
flex: 0 1 150px;
}
.input-block {
border: 1px solid black;
}
.block:hover {
background-color: rgb(231, 231, 231);
}
.row {
padding: 10px;
text-align: right;
color: rgb(61, 61, 61);
letter-spacing: 1.4px;
}
.row:first-child {
font-weight: bold;
color: rgb(83, 83, 83);
background-color: burlywood;
}
.row:nth-child(even) {
background-color: rgb(255, 241, 219);
}
.row-head:nth-child(even) {
background-color: rgb(205, 255, 200);
}
<body>
<div id="root"></div>
</body>
<script type="module">
import { html, render } from 'https://unpkg.com/lit-html?module';
function main() {
const arr = new Array(32).fill(0).map((x, i) => i);
const elements = arr.map(x => getBinaryAssociates(x));
let state = { elements }
display(state);
}
/**
* @param { { elements: ReturnType<typeof getBinaryAssociates>[] } } state
*/
function display(state) {
const root = document.getElementById("root");
/** @type {(_: typeof state) => any} */
const tmpl = (state) => html`<div class="container">
${getHeaderBlockTmpl()}
${state.elements.map(getItemBlockTmpl)}
<div>`;
render(tmpl(state), root);
}
function getHeaderBlockTmpl() {
return html`<div class="block input-block">
<div class="row row-head">Input</div>
${FUNCTIONS.map(x => html`<div class="row row-head">${x.toString()}</div>`)}
</div>`;
}
function getItemBlockTmpl(item) {
return html`<div class="block">
<div class="row">
${numToString(item.input)} ➡ ${item.binary}
</div>
${item.outputs.map(x => html`<div class="row">
${x.value} ➡ ${x.binary}
</div>`)}
</div>`;
}
const FUNCTIONS = [
x => x + 1,
x => x - 1,
x => x & (x - 1),
x => ~x + 1,
x => -(x + 1),
x => ~x,
];
function numToString(n) {
return n.toString();
}
function getBinaryAssociates(number) {
const binary = (x) => (x >>> 0).toString(2).slice(-6).padStart(6, '0');
let res = FUNCTIONS
.map(x => ({
function: x,
value: numToString(x(number)),
binary: binary(x(number)),
}));
let result = res.reduce((acc, n) => {
acc.outputs.push(n);
return acc;
}, {
input: number,
binary: binary(number),
/** @type {typeof res} */
outputs: [],
});
return result;
}
function init() {
document.addEventListener("DOMContentLoaded", () => {
main();
});
}
init();
</script>