From a86e20e93f0d55049b964f92da2cecb8750f1472 Mon Sep 17 00:00:00 2001 From: Greg Hurrell Date: Tue, 30 May 2017 23:59:07 -0700 Subject: [PATCH] Speed up by avoiding repeated regex construction etc Avoid repeated regexp allocation, `slice`, `trim` and `toLowerCase` calls. --- src/Field.react.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Field.react.js b/src/Field.react.js index 1c50e6d..f8314ab 100644 --- a/src/Field.react.js +++ b/src/Field.react.js @@ -33,6 +33,13 @@ function fromValue(value: ?Value, base: number): string { return convert(value.value, value.base, base); } +function getValidator(base) { + return new RegExp( + `^\\s*[${DIGITS.slice(0, base)}]*\\s*$`, + 'i' + ); +} + export default class Field extends React.Component { static propTypes = { base: PropTypes.number, @@ -50,14 +57,16 @@ export default class Field extends React.Component { `base prop must be between 2..${DIGITS.length}` ); } + this._validator = getValidator(props.base); this.state = {copySucceeded: false}; } + componentWillReceiveProps(nextProps) { + this._validator = getValidator(nextProps.base); + } + _isValid(value: string): boolean { - const validator = new RegExp( - `^[${DIGITS.slice(0, this.props.base)}]*$` - ); - return validator.test(value.trim().toLowerCase()); + return this._validator.test(value); } _onChange = event => { -- 2.37.1