Have you ever see yourself with a function (or method, depending on programming language) that has too many arguments and would be a lot better to switch to a single options
/params
/item
object?
This can be stressfull or painfull depending on all the regressions or usages of this functions. Even sometimes it can be a blind spot to how much that function is being used.
But no fear my friend, Rest Operators are here to save you! 🦸
Imagine you have an add to cart function:
const addItemToCart = (productId, quantity, size) => { // ommited for god's sake }
Time (and developers) goes by and we need to add more items to it, but it have so many usages that a refactor will be a hell of a work... After some years this function found itself as
const addItemToCart = (productId, quantity, size, hasPromotion, addedFrom, cartId, someOtherInfo) => { }
You wish you could change to a simple const addItemToCart = (itemData) =>
but that will make a simple task grows to a hell of a regressions and files to update, right?
Well let's start a painless refactor:
1 - of course change the functions arguments to be a single one:
const addItemToCart = (itemData) => { }
2 - let convert this argument to use Rest Operators:
const addItemToCart = (...itemData) => { }
3 last but not least let's apply conditional validation to use the arguments data:
const addItemToCart = (...itemData) => { let item = {}; if (typeof itemData[0] === 'object') { item = itemData[0]; else { const [ productId, quantity, size, hasPromotion, addedFrom, cartId, someOtherInfo ] = itemData; item = { productId, quantity, size, hasPromotion, addedFrom, cartId, someOtherInfo }; } }
And now all old keeps working and you can start write new function call with a prettier code 😉
Top comments (0)