Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active April 12, 2020 15:37
Show Gist options
  • Save stonehippo/11f60e2f90f7bebcbf354ca4dbb88cd3 to your computer and use it in GitHub Desktop.
Save stonehippo/11f60e2f90f7bebcbf354ca4dbb88cd3 to your computer and use it in GitHub Desktop.
Messing around with Ramda.js and some data manipulation
module.exports = {
names: ['Hester', 'Zelda', 'Millie', 'Pete', 'Mitchel', 'Fred'],
ages: [39, 11, 4, 18, 2, 43],
genders: ['female', 'non-binary', 'female', 'female', 'female', 'male'],
species: ['human', 'human', 'dog', 'cat', 'hamster', 'human'],
keys: ['name', 'age', 'gender', 'species']
}
// get some handy functional tools
const R = require('ramda')
// get some data
const D = require('./data')
// Note: in an earlier version of this code, I used destructuring on
// the imports, but it just added lines of code and obscured the
// where some things were defined.
// set up a pre-configured console.dir
const dirConfig = {
depth: null,
colors: true
}
const deepLog = R.partialRight(console.dir, [dirConfig])
// create a couple of utilities for data manipulation
const flatZip = R.zipWith((a,b) => R.flatten([a,b]))
const mapToObjectList = R.map(R.zipObj(D.keys))
// manipulate the data into a table
// Note: the accumulator for the reduce() starts with one of the values because zipWith()
// truncates to the lenth of the shortest array
const dataTable = R.reduce(flatZip, R.clone(D.names), [D.ages, D.genders, D.species])
deepLog(dataTable)
// turn the table into a list of objects
const dataList = mapToObjectList(dataTable)
deepLog(dataList)
{
"name": "ramda-data-tinkering",
"version": "1.0.0",
"dependencies": {
"ramda": "latest"
}
}

Ramda.js Data Tinkering

I'm messing around with manipulating a data structure in Node.js using Ramda.js . Mostly I'm trying things like turning some data into a unified table based on a series of arrays (sort of like a database denormalization), and with some alternatives to the pre-packaged zip functions in the library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment