Created
March 24, 2021 09:01
-
-
Save riazXrazor/5ae5cadbf00f273f188ed8a40402e5bc to your computer and use it in GitHub Desktop.
Calculate Average of numbers in an array in a functional way
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
// Helpers | |
// ---------------------------------------------------------------------------- | |
const filter = p => a => a.filter(p); | |
const map = f => a => a.map(f); | |
const reduce = r => i => a => a.reduce(r, i); | |
// Lift for functions. to understand this use below link 👇 | |
// See: https://jrsinclair.com/articles/2019/compose-js-functions-multiple-parameters/ | |
const lift = f => g => h => x => f(g(x))(h(x)); | |
// Calculations | |
// ---------------------------------------------------------------------------- | |
// A sum function that adds all the items of an array together. | |
const sum = reduce((a, i) => a + i)(0); | |
// A function to get the length of an array. | |
const length = a => a.length; | |
// A function to divide one number by another. | |
const div = a => b => a / b; | |
// Usage | |
// ---------------------------------------------------------------------------- | |
const ArrOfNum = [1,2,3,4,5,6,7,8] | |
const calcAvg = lift(div)(sum)(length) | |
console.log(calcAvg(ArrOfNum)) // 4.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment