'JavaScript - Refactor the way we pass args to function
I have implemented the following method:
async function sendPushNotifications(
title,
body,
data,
badge,
sound = "default",
pushNotificationsTokens
) {
// Generate the messages to be sent
const messages = buildMessages(
title,
body,
data,
badge,
sound,
pushNotificationsTokens
);
// Send the generated messages to the FCM server
const tickets = await sendMessagesToFCMServer(messages);
// Finally, handle all possible errors to avoid app removal in stores
await handleErrorsSendingMessages(tickets, pushNotificationsTokens);
}
And I want to expose a simpler method, for sending a push notification to a unique token.
function sendPushNotification(
title,
body,
data,
badge,
sound = "default",
pushNotificationsToken
) {
return sendPushNotifications(
title,
body,
data,
badge,
sound,
[pushNotificationsToken]
);
}
As you can see, there is some kind of pattern here. We get the params and just pass them to the other method, but pushing the pushNotificationsToken into an array.
My question is: is it possible to refactor the second function sendPushNotification? I mean, any professional look-alike functional code to do it in one line?
Solution 1:[1]
Using rest parameters and popping off the last one and putting it into an array instead would work.
const sendPushNotification = (...args) => {
const token = args.pop();
return sendPushNotifications(...args, [token]);
};
It'd technically be possible to shove it all into one line (you can put entire applications on a single line if you wanted), but that'd be less readable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
