parent
d3e4e51b86
commit
1be005669e
8 changed files with 92 additions and 15 deletions
@ -0,0 +1,56 @@ |
||||
import testRange from './testRange'; |
||||
import toNumber from '../toNumber'; |
||||
|
||||
const buildNumberTestBatch: BuildInputTestBatchFunction = ( |
||||
inputName, |
||||
onSuccess, |
||||
{ onFinishBatch, ...defaults } = {}, |
||||
onIntTestFailure?, |
||||
onFloatTestFailure?, |
||||
onRangeTestFailure?, |
||||
) => { |
||||
const tests: InputTest[] = []; |
||||
|
||||
if (onIntTestFailure) { |
||||
tests.push({ |
||||
onFailure: (...args) => { |
||||
onIntTestFailure(<>{inputName} must be a valid integer.</>, ...args); |
||||
}, |
||||
test: ({ value }) => Number.isSafeInteger(toNumber(value)), |
||||
}); |
||||
} else if (onFloatTestFailure) { |
||||
tests.push({ |
||||
onFailure: (...args) => { |
||||
onFloatTestFailure( |
||||
<>{inputName} must be a valid floating-point number.</>, |
||||
...args, |
||||
); |
||||
}, |
||||
test: ({ value }) => Number.isFinite(toNumber(value, 'parseFloat')), |
||||
}); |
||||
} |
||||
|
||||
if (onRangeTestFailure) { |
||||
tests.push({ |
||||
onFailure: (...args) => { |
||||
const { displayMax, displayMin } = args[0]; |
||||
|
||||
onRangeTestFailure( |
||||
<> |
||||
{inputName} is expected to be between {displayMin} and {displayMax}. |
||||
</>, |
||||
...args, |
||||
); |
||||
}, |
||||
test: testRange, |
||||
}); |
||||
} |
||||
|
||||
return { |
||||
defaults: { ...defaults, onSuccess }, |
||||
onFinishBatch, |
||||
tests, |
||||
}; |
||||
}; |
||||
|
||||
export default buildNumberTestBatch; |
@ -0,0 +1,7 @@ |
||||
const toNumber: ( |
||||
value: unknown, |
||||
parser?: 'parseFloat' | 'parseInt', |
||||
) => number = (value, parser = 'parseInt') => |
||||
typeof value === 'number' ? value : Number[parser](String(value)); |
||||
|
||||
export default toNumber; |
Loading…
Reference in new issue