I have three pretty similar functions:
//for context there is also this part:
const [colors, setColors] = useState(["#000000", "#ffffff"]);
// but the three functions start here:
function updateColor(index, color) {
const newColors = [...colors];
newColors[index] = color;
setColors(newColors);
}
function deleteColor(index) {
const newColors = [...colors];
newColors.splice(index, 1);
setColors(newColors);
}
function duplicateColor(index) {
const newColors = [...colors];
newColors.splice(index, 0, newColors[index]);
setColors(newColors);
}
As you can see the first and third line of each of these are identical. Is there some method by which I can create a function that takes the middle line as a callback function and reproduces the first and third.
Something like:
const updateColor = functionMaker((index, color) => newColors[index]);
const deleteColor = functionMaker((index) => newColors.splice(index, 1));
I can’t quite get my head around how I would support different arguments for each, as in my example above.
3
Answers
Create a function that accepts a callback and returns a function that creates
newColor
and delegates that along with its arguments to the callback:Try it:
you can do it like so
then use it like so,
One approach is to use the Strategy Pattern as shown below. However, please note that this example is not well-encapsulated, and frankly removing those two lines of code might not be worth creating the abstraction.