Skip to content

Instantly share code, notes, and snippets.

@robertpenner
Last active June 26, 2020 23:16
Show Gist options
  • Save robertpenner/f02bb38553adb09ec09e2e265c01c750 to your computer and use it in GitHub Desktop.
Save robertpenner/f02bb38553adb09ec09e2e265c01c750 to your computer and use it in GitHub Desktop.
Employee Average Salaries | Victor Savkin's Functional TypeScript
// https://vsavkin.com/functional-typescript-316f0e003dc6
class Employee {
constructor(public name: string, public salary: number) {}
}
class Department {
constructor(public employees: Employee[]) {}
works(employee: Employee): boolean {
return this.employees.indexOf(employee) > -1;
}
}
type Predicate<T> = (value: T) => boolean;
function and<T>(predicates: Predicate<T>[]): Predicate<T> {
return (value) => predicates.every(p => p(value));
}
function filteredSalaries(employees: Employee[], conditions: Predicate<Employee>[]): number[] {
const filtered = employees.filter(and(conditions));
return filtered.map(e => e.salary);
}
function average(nums: number[]): number {
const total = nums.reduce((a,b) => a + b, 0);
return total / nums.length;
}
function averageFilteredSalary(employees: Employee[], conditions: Predicate<Employee>[]): number {
return average(filteredSalaries(employees, conditions));
}
const empls = [
new Employee("Jim", 100),
new Employee("John", 200),
new Employee("Liz", 120),
new Employee("Penny", 30)
];
const sales = new Department([empls[0], empls[1]]);
const conditions = [
(employee) => employee.salary > 50,
(employee) => sales.works(employee)
];
const salesAverageSalaryOver50 = averageFilteredSalary(empls, conditions);
console.log('salesAverageSalaryOver50:', salesAverageSalaryOver50);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment