Skip to content

Instantly share code, notes, and snippets.

@joemsak

joemsak/1home.js

Last active Aug 19, 2017
Embed
What would you like to do?
import { h, Component } from 'preact';
import style from './style';
export default class Home extends Component {
constructor() {
super();
this.instructions = {
"B,s1": ["X", "R", "s2"],
"B,s2": ["B", "L", "s3"],
"X,s3": ["B", "R", "s4"],
"B,s4": ["B", "L", "s1"],
}
this.state = {
tape: ["B", "B"],
head: 0,
machineState: "s1",
}
}
renderTapeCells() {
return this.state.tape.map(function(cell) {
return (
<span class={style.tape_cell}>
{cell}
</span>
);
});
}
renderHeadPos() {
if (this.state.head === 0) {
return(
<div id={style.head}>
<span>^</span>
</div>
);
} else {
return(
<div id={style.head}>
<span class={style.hide}>B</span>
<span>^</span>
</div>
);
}
}
simulate() {
var tape = this.state.tape,
value = tape[this.state.head],
key = [value, this.state.machineState].join(","),
[next_value, next_action, next_machine_state] = this.instructions[key];
tape[this.state.head] = next_value;
this.setState({
tape: tape,
head: this.state.head + (next_action == "R" ? 1 : -1),
machineState: next_machine_state,
});
}
componentDidMount() {
setInterval(this.simulate.bind(this), 500);
}
render() {
return (
<div class={style.home}>
<div id={style.tape}>{this.renderTapeCells()}</div>
{this.renderHeadPos()}
</div>
);
}
}
.home {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%, -50%);
font-size: 5rem;
}
.tape_cell {
display: inline-block;
padding: 1rem;
font-weight: bold;
border: 1px solid #ccc;
margin-right: 1rem;
}
#tape {
margin: 0;
display: flex;
flex-direction: row;
}
#head {
margin: 0;
display: flex;
flex-direction: row;
}
#head span {
display: inline-block;
padding: 0 1rem;
font-weight: bold;
margin-right: 1rem;
}
.hide {
opacity: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment