const MAX_LENGTH = 10;
function CounterInput({value,defaultValue,onChange}){
const [stateValue,setStateValue] = useState(defaultValue);
const [counter,setCounter] = useState(0);
const handleChange = useCallback((e)=>{
const inputValue = e.target.value;
if(inputValue.length <= MAX_LENGTH){
setStateValue(inputValue);
setCounter(inputValue.length);
}else{
throw new Error('Length of input value must less then MAX_LENGTH(10)')
}
},[])
const isControlled = useMemo(()=>defaultValue === undefined,[defaultValue]);
return(
<div style={{display:'inline-block'}}>
<input value={isControlled?value:stateValue} onChange={isControlled?onChange:handleChange} />
<span>{counter+'/'+MAX_LENGTH}</span>
</div>
)
}
function convert(money){
if(typeof money !== 'number'||money < 0 ){
throw new Error('...')
}
const moneySplits = (money+'').split('.');
const left = moneySplits[0];
const reg = /(\d)(?=(?:\d{3})+$)/g;
const resLeft = left.replace(reg,'$1,');
return resLeft + '.' + moneySplits[1];
}
function convert(money){
return money.toLocaleString();
}