Last active
March 8, 2019 13:27
-
-
Save zaguiini/d35ced87442113ab39d27dfa0442c8d1 to your computer and use it in GitHub Desktop.
Useful hook for when updating multiple values that must fit 100%
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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