Skip to content

Instantly share code, notes, and snippets.

@zaguiini
Last active March 8, 2019 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaguiini/d35ced87442113ab39d27dfa0442c8d1 to your computer and use it in GitHub Desktop.
Save zaguiini/d35ced87442113ab39d27dfa0442c8d1 to your computer and use it in GitHub Desktop.
Useful hook for when updating multiple values that must fit 100%
function useMutualNumberField({
values,
index,
setCurrentValue,
setAllValues,
}) {
return function handlePercentageChange(rawInputtedValue) {
const inputtedValue = parseInt((rawInputtedValue || 0).toString(), 10)
const prevValue = values[index].percentage
let remainingPercentage =
100 -
values.reduce(
(curr, next) => curr + (next.percentage || 0),
0
)
if (values.length === 1) {
if (
(remainingPercentage > 0 && inputtedValue <= 100) ||
prevValue > inputtedValue
) {
setCurrentValue(inputtedValue)
}
} else {
const newValue = values.slice()
const valueToBeModified = values[index + 1] ? index + 1 : index - 1
remainingPercentage -= inputtedValue + prevValue * -1
if (remainingPercentage < 0 && inputtedValue > prevValue) {
const allValuesExceptCurrent = values.reduce(
(curr, next, i) =>
i === index ? curr : curr + next.percentage,
0
)
newValue[valueToBeModified].percentage -=
inputtedValue + allValuesExceptCurrent - 100
}
newValue[index].percentage = inputtedValue
if (newValue[valueToBeModified].percentage <= 0) {
newValue.splice(valueToBeModified, 1)
}
setAllValues(newValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment