Functional Programming Example – using Ramda

Share

Functional Programming Example – using Ramda

Copy and paste this code into your console. It automatically loads Ramda and uses that to process the beerData.

Two concepts covered in this example:

  • Loading external scripts into the console (which works in chrome developer tools snippets at minimum). I can’t seem to find a way to make it work in firefox.
  • Functional programming.

#functional, #loadingScripts

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//cdnjs.cloudflare.com/ajax/libs/ramda/0.21.0/ramda.min.js';
document.head.appendChild(script);

beerData = [
    {"name": "Bitter Hop", "type": "ipa", "locale": "domestic", "abv": 7.9},
    {"name": "Dragonblood Black IPA", "type": "ipa", "locale": "domestic", "abv": 6.5},
    {"name": "Good Dog Lager", "type": "lager", "locale": "domestic", "abv": 4.8},
    {"name": "Good Dog Snowpants", "type": "stout", "locale": "domestic", "abv": 8.1},
    {"name": "Lake Erie 2x IPA", "type": "ipa", "locale": "domestic", "abv": 9.3},
    {"name": "Lake Erie Session", "type": "ale", "locale": "domestic", "abv": 4.2},
    {"name": "Samwell British Pale Ale", "type": "ale", "locale": "import", "abv": 6.5},
    {"name": "Samwell Oatmeal Stout", "type": "stout", "locale": "import", "abv": 5.5},
    {"name": "Samwell Winter Ale", "type": "ale", "locale": "import", "abv": 6.8},
    {"name": "Sparkwood Beer Five", "type": "lager", "locale": "domestic", "abv": 6.2},
    {"name": "Sparkwood Campfire Lager", "type": "lager", "locale": "domestic", "abv": 5.8},
    {"name": "Tartan Scottish Ale", "type": "ale", "locale": "import", "abv": 7.5}
]

console.clear();

console.log('beerData:');
console.table(beerData);

var uniqueTypes = R.pipe(R.pluck('type'), R.uniq, R.sort((a, b) => a > b));
var typeList = uniqueTypes(beerData);

console.log('typeList: ', typeList);

var displayBeerByType = R.pipe(
    R.propEq('type'),
    R.filter(R.__, beerData),
    console.table.bind(console)
);


R.forEach(displayBeerByType, typeList);
Share

Leave a Reply

Your email address will not be published. Required fields are marked *