Problem:
We have multiple functions that are pretty similar, with a minor difference. So it would be great to get rid of the duplicated code.
async function createUser(user: User): Promise<void> {
LoadingService.startLoading();
await userHttpClient.createUser(user);
LoadingService.stopLoading();
UserGrid.reloadData();
}
async function updateUser(user: User): Promise<void> {
LoadingService.startLoading();
await userHttpClient.updateUser(user);
LoadingService.stopLoading();
UserGrid.reloadData();
}
Solution:
We can extract the code that changes and pass it through the callback. In such a manner, we’ll remove duplicate code.
async function makeUserAction(fn: Function): Promise<void> {
LoadingService.startLoading();
await fn();
LoadingService.stopLoading();
UserGrid.reloadData();
}
async function createUser2(user: User): Promise<void> {
makeUserAction(() => userHttpClient.createUser(user));
}
async function updateUser2(user: User): Promise<void> {
makeUserAction(() => userHttpClient.updateUser(user));
}