Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created December 24, 2015 19:25
Show Gist options
  • Save bennadel/7db33e18cbf7186b78af to your computer and use it in GitHub Desktop.
Save bennadel/7db33e18cbf7186b78af to your computer and use it in GitHub Desktop.
The Best Way To Compute The Average Age Of Cat Owners In Functional Programming
var _ = require( "lodash" );
// Assume a collection that has:
// - age: Number
// - hasCat: Boolean
var people = require( "./people.json" );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
var reduction = _.reduce(
people,
function operator( accumulator, person ) {
if ( person.hasCat ) {
accumulator.sum += person.age;
accumulator.count++;
accumulator.average = ( accumulator.sum / accumulator.count );
}
return( accumulator );
},
{
sum: 0,
count: 0,
average: 0
}
);
console.log( "Average age of cat owner: %s", reduction.average );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
var averageAge = _.reduce(
_.pluck(
_.where(
people,
{
hasCat: true
}
),
"age"
),
function operator( average, age, index, collection ) {
return( average + ( age / collection.length ) );
},
0
);
console.log( "Average age of cat owner: %s", averageAge );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
var catOwners = _.where( people, { hasCat: true } );
var averageAge = ( _.sum( _.pluck( catOwners, "age" ) ) / catOwners.length );
console.log( "Average age of cat owner: %s", averageAge );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
var averageAge = _.chain( people )
.where({ hasCat: true })
.pluck( "age" )
.reduce(
function operator( sum, age, index, collection ) {
return ( index === ( collection.length - 1 ) )
? ( ( sum + age ) / collection.length )
: ( sum + age )
;
},
0
)
.value()
;
console.log( "Average age of cat owner: %s", averageAge );
console.log( "Average age of cat owner: %s", getAverageAgeOfCatOwners( people ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment