Created
July 11, 2022 20:43
-
-
Save haase1020/d09f2cee03a9d4550276feab46ba95f1 to your computer and use it in GitHub Desktop.
simple example of a higher order function
This file contains 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
enum SIZE { | |
small = 'small', | |
medium = 'medium', | |
large = 'large' | |
} | |
function calculateAge(operation: Function, initialVal: number, factor: boolean | SIZE) { | |
const age = operation(initialVal, factor) | |
return age; | |
} | |
function computeDogAge(years: number, size: SIZE) { | |
if (size === SIZE.small || size === SIZE.medium) { | |
return years * 5; | |
} else if (size === SIZE.large) { | |
return years * 7; | |
} else { | |
return years * 7; | |
} | |
} | |
function computePeopleAge(years: number, exercise: boolean) { | |
if (exercise) { | |
return years; | |
} else { | |
return years + 5; | |
} | |
} | |
function computeCatAge(years: number, indoor: boolean) { | |
if (indoor) { | |
return years * 5; | |
} else { | |
return years * 7; | |
} | |
} | |
console.log(calculateAge(computeDogAge, 4, SIZE.medium)) | |
console.log(calculateAge(computePeopleAge, 20, true)) | |
console.log(calculateAge(computeCatAge, 3, true)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment