Created
May 6, 2021 15:19
-
-
Save leonidkuznetsov18/cdb9f6096a41ebbeacd0bd012d3c718b to your computer and use it in GitHub Desktop.
exercise with reduce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| mocha.setup('bdd'); | |
| var expect = chai.expect; | |
| const employees = [ | |
| { name: "Barak Obama", role: "president", pay: 35000 }, | |
| { name: "Noa Kirel", role: "artist", pay: 1000000 }, | |
| { name: "Donald Trump", role: "president", pay: 40000 }, | |
| { name: "Tova Cohen", role: "teacher", pay: 135210 }, | |
| { name: "Ivri Lider", role: "artist", pay: 32000 }, | |
| { name: "Dan Bilzarian", role: "player", pay: 12000000 }, | |
| { name: "Roni Levi", role: "teacher", pay: 51000 }, | |
| ]; | |
| function findMax() { | |
| // return name and pay of max paid employee | |
| return employees.reduce((a, b) => { | |
| return a.pay > b.pay ? a : b | |
| }) | |
| } | |
| function findAverage() { | |
| // return average pay | |
| const length = employees.length; | |
| const sum = employees.reduce((acc, curr) => { | |
| return acc + curr.pay; | |
| }, 0); | |
| return sum / length; | |
| } | |
| function averageByRole() { | |
| // return an object {[role]: average pay per role} | |
| const obj = employees.reduce((acc, curr) => { | |
| acc[curr.role] = acc[curr.role] || {role: curr.role, pay: 0, count: 0}; | |
| acc[curr.role].count += 1 | |
| acc[curr.role].pay += curr.pay | |
| return acc; | |
| }, {}) | |
| for(key in obj) { | |
| obj[key] = obj[key].pay / obj[key].count | |
| } | |
| return obj; | |
| } | |
| console.log(averageByRole()) | |
| describe('find max', () => { | |
| it('should return name and pay of highest paid employee', () => { | |
| const max = findMax(); | |
| expect(max.pay).to.equal(12000000); | |
| expect(max.name).to.equal("Dan Bilzarian"); | |
| }); | |
| }); | |
| describe('find average', () => { | |
| it('should return average salary', () => { | |
| const averageSalary = findAverage(); | |
| expect(averageSalary).to.equal(1899030); | |
| }); | |
| }); | |
| describe('average by role', () => { | |
| it('should return object with average pay per role', () => { | |
| const averageSalaryByRole = averageByRole(); | |
| expect(averageSalaryByRole).to.deep.equal({ | |
| artist: 516000, | |
| player: 12000000, | |
| president: 37500, | |
| teacher: 93105 | |
| }); | |
| }); | |
| }); | |
| mocha.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment