Rating Credit Scores: Solution Review
Solution review.
Since score
is an array of numbers, we know map
's involved. It lets us loop and transform each score as we see fit.
What would we do with each score? Let’s review the challenge.
- At or above 800, return “{score} is excellent!”
- At or above 700, return “{score} is good”
- At or above 650, return “{score} is fair”
- At or below 649, return “{score} is poor”
Imperatively, that sounds like a bunch of if/else
statements.
const reviewCreditScore = (score) => {if (score >= 800) {return `${score} is excellent!`;}if (score >= 700) {return `${score} is good`;}if (score >= 650) {return `${score} is fair`;}if (score <= 649) {return `${score} is poor`;}};console.log(reviewCreditScore(630));
Luckily though, Ramda has us covered. cond
can easily replace this logic with functions!
import { cond } from 'ramda';const reviewCreditScore = cond([[(score) => score >= 800, (score) => `${score} is excellent!`],[(score) => score >= 700, (score) => `${score} is good`],[(score) => score >= 650, (score) => `${score} is fair`],[(score) => score <= 649, (score) => `${score} is poor`]]);console.log(reviewCreditScore(800));
It does look a bit confusing with all the arrows, however.
If you’d like to make the comparisons point-free, try gte
and lte
.
index.js
scores.json
import { cond, gte, lte } from 'ramda';const reviewCreditScore = cond([[lte(800), (score) => `${score} is excellent!`],[lte(700), (score) => `${score} is good`],[lte(650), (score) => `${score} is fair`],[gte(649), (score) => `${score} is poor`]]);console.log(reviewCreditScore(800));
Now compose it with map
to review all the scores!
index.js
scores.json
import { cond, gte, lte, map } from 'ramda';import scores from './scores.json';const reviewCreditScore = cond([[lte(800), (score) => `${score} is excellent!`],[lte(700), (score) => `${score} is good`],[lte(650), (score) => `${score} is fair`],[gte(649), (score) => `${score} is poor`]]);const reviewCreditScores = map(reviewCreditScore);console.log(reviewCreditScores(scores));