From: Greg Hurrell Date: Sat, 1 Aug 2015 14:06:14 +0000 (-0700) Subject: Avoid unnecessary base conversions X-Git-Url: https://git.wincent.com/hextrapolate.git/commitdiff_plain/0bbe2f253cc7e8ed31bd5117833c83b423845824 Avoid unnecessary base conversions Instead of converting to a canonical hexadecimal base format, let the updating component juts pass back the raw value + base. This should cut the number of conversions by about 25%. For example, if I change the binary field, instead of converting to hexadecimal once, then from hexadecimal to some other base for three of the four fields (ie. four total conversions), we instead just convert three fields. --- diff --git a/src/App.js b/src/App.js index 259457f..81bef69 100644 --- a/src/App.js +++ b/src/App.js @@ -8,6 +8,7 @@ 'use strict'; import React from 'react'; +import type Value from './Field.react'; import Field from './Field.react'; import Label from './Label.react'; @@ -21,7 +22,7 @@ export default class App extends React.Component { }; } - _onValueChange = (value: string) => { + _onValueChange = (value: Value) => { this.setState({value}); } diff --git a/src/Field.react.js b/src/Field.react.js index 4cd7d47..382aa78 100644 --- a/src/Field.react.js +++ b/src/Field.react.js @@ -10,39 +10,34 @@ import React from 'react'; import convert from './convert'; +export type Value = { + base: number; + value: string; +}; +export const ValuePropType = React.PropTypes.shape({ + base: React.PropTypes.number, + value: React.PropTypes.string, +}); + const DIGITS = '0123456789abcdef'; /** - * Convert from canonical (hexadecimal) value to `base`. + * Convert from `value` to `base`. */ -function fromValue(value: string, base: number): string { +function fromValue(value: ?Value, base: number): string { if (value === null) { return ''; + } else if (value.base === base) { + return value.value; } - if (base === 16) { - return value; - } - return convert(value, 16, base); -} - -/** - * Convert from `base` value to canonical (hexadecimal) value. - */ -function toValue(value: string, base: number): ?string { - if (value === '') { - return null; - } - if (base === 16) { - return value; - } - return convert(value, base, 16); + return convert(value.value, value.base, base); } export default class Field extends React.Component { static propTypes = { base: React.PropTypes.number, onValueChange: React.PropTypes.func.required, - value: React.PropTypes.string.required, + value: ValuePropType, }; static defaultProps = { base: 10, @@ -67,7 +62,10 @@ export default class Field extends React.Component { _onChange = event => { const value = event.currentTarget.value; if (this._isValid(value)) { - this.props.onValueChange(toValue(value, this.props.base)); + this.props.onValueChange({ + base: this.props.base, + value, + }); } }