Skip to content

Instantly share code, notes, and snippets.

@riazXrazor
Created March 24, 2021 09:01
Show Gist options
  • Save riazXrazor/5ae5cadbf00f273f188ed8a40402e5bc to your computer and use it in GitHub Desktop.
Save riazXrazor/5ae5cadbf00f273f188ed8a40402e5bc to your computer and use it in GitHub Desktop.
Calculate Average of numbers in an array in a functional way
// 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