Support for flipable bits

This commit is contained in:
BorysLevytskyi
2016-11-22 20:09:41 +02:00
parent bece4ffc8d
commit 90b26032c7
2 changed files with 58 additions and 20 deletions

View File

@@ -12,15 +12,43 @@ export default class ListOfNumersExpressionView extends React.Component {
}
class OperandView extends React.Component {
componentWillMount() {
this.setState(this.props.operand);
}
render() {
const op = this.props.operand;
console.log(this.props);
// const bitsSize = this.propsю;
// .padLeft(m.bitsSize, '0')
return <tr data-kind={op.kind}>
const op = this.state;
const binaryString = formatter.padLeft(op.bin, this.props.maxBitsLegnth, '0');
return <tr data-kind={op.kind}>
<td className="label">{op.input}</td>
<td className="bin">{formatter.padLeft(op.bin, this.props.maxBitsLegnth, '0')}</td>
<td className="bin"><ClickableBinary binaryString={binaryString} onFlipBit={i => this.flipBit(i)} /></td>
<td className="other">{op.other}</td>
</tr>
};
flipBit(index) {
var op = this.props.operand;
const binaryString = formatter.padLeft(op.bin, this.props.maxBitsLegnth, '0');
var arr = binaryString.split('');
arr[index] = arr[index] == '0' ? '1' : '0';
op.update(arr.join());
this.setState(op);
}
}
class ClickableBinary extends React.Component {
render() {
const str = this.props.binaryString;
const chars = str.split('');
const classNames = { '0': 'zero flipable', '1' : 'one flipable' };
const children = chars.map((c, i) => <span className={classNames[c]} key={i} onClick={e => this.onBitClick(i, e)}>{c}</span>);
return <span>{children}</span>
}
onBitClick(index, e) {
if(this.props.onFlipBit) {
this.props.onFlipBit(index);
}
}
}

View File

@@ -131,19 +131,7 @@ export class Operand {
return Math.floor(Math.log(this.value) / Math.log(2)) + 1;
};
toKindString(value, kind) {
switch(kind) {
case 'hex':
var hexVal = Math.abs(value).toString(16);
return value >= 0 ? '0x' + hexVal : '-0x' + hexVal;
case 'bin':
return (value>>>0).toString(2);
case 'dec':
return value.toString(10);
default:
throw new Error("Unexpected kind: " + kind)
}
};
getOtherKind(kind) {
switch(kind) {
@@ -156,7 +144,15 @@ export class Operand {
toString() {
return this.input;
}
update(binary) {
this.value = parseInt(2);
this.bin = binary;
this.dec = Operand.toKindString(this.value, 'dec');
this.hex = Operand.toKindString(this.value, 'hex');
}
static getBitLength(num) {
return Math.floor(Math.log(num) / Math.log(2)) + 1
}
@@ -178,6 +174,20 @@ export class Operand {
return new Operand(str);
};
static toKindString(value, kind) {
switch(kind) {
case 'hex':
var hexVal = Math.abs(value).toString(16);
return value >= 0 ? '0x' + hexVal : '-0x' + hexVal;
case 'bin':
return (value>>>0).toString(2);
case 'dec':
return value.toString(10);
default:
throw new Error("Unexpected kind: " + kind)
}
};
static toHexString (hex) {
return hex.indexOf('-') == 0 ? '-0x' + hex.substr(1) : '0x' + hex;
};