Skip to content

Instantly share code, notes, and snippets.

@itrav
Created June 5, 2018 02:19
Show Gist options
  • Save itrav/36d653b944d273c62b9554522fb845f7 to your computer and use it in GitHub Desktop.
Save itrav/36d653b944d273c62b9554522fb845f7 to your computer and use it in GitHub Desktop.
let data = [2, 4, 6, 8];
mean(data); // => 5.0
// common way
const mean = function (xs) {
let n = xs.length;
return xs.reduce((m, x) => m + x / n, 0);
};
// using ES6 default parameters and IIFE to emulate
// functional style let-expressions
const mean = xs =>
((n = xs.length) => xs.reduce((m, x) => m + x / n, 0))();
// "unprotected" let-expressions (variables can be set
// to unexpected values)
const mean = (xs, n = xs.length) =>
xs.reduce((m, x) => m + x / n, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment