Idea
const sum = (arr) => arr.reduce((a, b) => a + b, 0)
Improved version Argument can be numbers or strings or array of them.
const sum = (...nums) => {
let arr = []
// may pass array or args separately
if (!Array.isArray(nums)) arr = [...nums] // if primitive args supplied
if (Array.isArray(nums)) arr = nums.flat(Infinity) // if array supplied
const floatsArr = arr.map(el => parseFloat(el)) // in case numbers are passed as strings
const sum = floatsArr.reduce((accum, curVal) => accum + curVal, 0)
return sum
}
Component
function Component() {
const [inputValState, setInputValState] = React.useState('1 2 3 4 5')
const [sumState, setSumState] = React.useState(sum(inputValState.split(' ')))
const onChangeHandler = (e) => {
const inpVal = e.target.value
setInputValState(inpVal)
const numsArr = inpVal
.match(/[-]{0,1}[\d]*[.]{0,1}[\d]+/g) // match numbers
.filter(el => el) // remove empty elements
setSumState(sum(numsArr))
}
return (
<>
<input value={inputValState} onChange={onChangeHandler}/>
<div>sum: {sumState}</div>
</>
)
}