I'm building a simple app using RamdaJS that aims to take a list of objects that represent U.S. states, and for each state, it should calculate the number of electoral votes and add that value as a new property to each object, called electoralVotes. The basic gist of the calculation itself (as inaccurate as it may be) is to divide the population by 600000, round that number down, and if the rounded-down number is 0, round it up to 1.
For simplicity, the array of states only includes a state name and population for each state:
const states = [
{ state: 'Alabama', population: 4833722 },
{ state: 'Alaska', population: 735132 },
{ state: 'Arizona', population: 6626624 },
// ... etc.
];
I created a function called getElectoralVotesForState that is created with nested levels of composition (A composed function that is built using another composed function). This function takes a state object, examines its population property, then calculates and returns the corresponding number of electoral votes.
const R = require('ramda');
// This might not be factually accurate, but it's a ballpark anyway
const POP_PER_ELECTORAL_VOTE = 600000;
const populationLens = R.lensProp("population");
// Take a number (population) and calculate the number of electoral votes
// If the rounded-down calculation is 0, round it up to 1
const getElectoralVotes = R.pipe(
R.divide(R.__, POP_PER_ELECTORAL_VOTE),
Math.floor,
R.when(R.equals(0), R.always(1))
);
// Take a state object and return the electoral votes
const getElectoralVotesForState = R.pipe(
R.view(populationLens),
getElectoralVotes
);
If I want to pass in a single state to the getElectoralVotesForState function, it works fine:
const alabama = { state: 'Alabama', population: 4833722 };
const alabamaElectoralVotes = getElectoralVotesForState(alabama); // Resolves to 8
While this seems to work for a single object, I can't seem to get this to apply to an array of objects. My guess is that the solution might look something like this:
const statesWithElectoralVotes = R.map(
R.assoc("electoralVotes", getElectoralVotesForState)
)(states);
This does add an electoralVotes property to each state, but it's a function and not a resolved value. I'm sure it's just a silly thing I'm getting wrong here, but I can't figure it out.
What am I missing?