Hey there, I've been given a task to optimize a program that is running too slow. The goal is to make it run faster.
interface Payroll {
empNo: string;
vacationDays: number;
}
interface AddressBook {
empNo: string;
email: string;
}
interface WorkHistory {
empNo: string;
name: string;
yearsEmployed: number;
}
interface EmailApi {
sendEmail(email: string, body: string);
}
// We decided to grant bonus vacation days to employees based on their years of experience
// and then notify them via email
EmailVacationGrant(
emailApi: EmailApi,
workHistory: WorkHistory[],
addressBook: AddressBook[],
payroll: Payroll[]
) {
for(let i=0; i<workHistory.length; ++i) {
let employee = wh[i];
let address = addressBook.find(x => x.empNo==employee.empNo);
let payroll = payroll.find(x => x.empNo==employee.empNo);
let newVacationBalance = employee.yearsEmployed + payroll.vacationDays;
emailApi.sendEmail(
address.email,
`Dear ${employee.name}\n` +
`You have been granted ${employee.yearsEmployed} days of vacation, bringing your total to ${newVacationBalance}`);
}
}
Upon researching, I discovered that browsers do not efficiently handle the .find method and prefer traditional for loops. To rectify this, I amalgamated everything into one interface. Here's my improved solution:
interface WorkHistory {
empNo: string;
vacationDays: number;
email: string;
name: string;
yearsEmployed: number;
}
interface EmailApi {
sendEmail(email: string, body: string);
}
// Grant bonus vacation days to employees based on experience and send notification emails
EmailVacationGrant(
emailApi: EmailApi,
workHistory: WorkHistory[]
) {
for(let i=0; i<workHistory.length; ++i) { // A for loop is faster in JavaScript than .find, but I wanted to maintain complexity
let employee = wh[i];
let address = employee.email;
let payroll = employee.payroll;
let newVacationBalance = employee.yearsEmployed + employee.vacationDays;
emailApi.sendEmail(
employee.email,
`Dear ${employee.name}\n` +
`You've been granted ${employee.yearsEmployed} days of vacation, bringing your balance to ${newVacationBalance}`);
}
}
Are there any other faster alternatives that don't involve tinkering with interfaces?