Skip to content

Instantly share code, notes, and snippets.

@danscotton
Last active August 29, 2015 14:20
Show Gist options
  • Save danscotton/a518824d63389e4b71ab to your computer and use it in GitHub Desktop.
Save danscotton/a518824d63389e4b71ab to your computer and use it in GitHub Desktop.
Monday Code Challenge: Transform data tables
Background:
Given the following mixes data
| 1 | Metal | Heavy metal | Track A |
| | | | Track B |
| | | | Track C |
| | | Hair metal | Track D |
| | | | Track E |
| | | | Track F |
| 2 | Dance | House | Track G |
| | | | Track H |
| | | | Track I |
| | | Trance | Track J |
| | | | Track K |
| | | | Track L |
// This is the JS output from cucumber from the above data table
var data = [
['1', 'Metal', 'Heavy metal', 'Track A'],
['', '', '', 'Track B'],
['', '', '', 'Track C'],
['', '', 'Hair metal', 'Track D'],
['', '', '', 'Track E'],
['', '', '', 'Track F'],
['2', 'Dance', 'House', 'Track G'],
['', '', '', 'Track H'],
['', '', '', 'Track I'],
['', '', 'Trance', 'Track J'],
['', '', '', 'Track K'],
['', '', '', 'Track L']
];
// I want this data structure created. You need to look into generating the ids (_.uniqueId() for e.g.)
var groups = [
{
id: 123, // generate id
name: 'Metal',
category: 'genre', // based off 1 in the first column
mixes: [
{
id: '001', // generate id
name: 'Heavy Metal',
tracks: [
{ name: 'Track A' },
{ name: 'Track B' },
{ name: 'Track C' }
]
},
{
id: '002', // generate id
name: 'Hair Metal',
tracks: [
{ name: 'Track D' },
{ name: 'Track E' },
{ name: 'Track F' }
]
}
]
},
{
id: 234, // generate id
name: 'Dance',
category: 'theme', // based off 2 in the first column
mixes: [
{
id: '003', // generate id
name: 'House',
tracks: [
{ name: 'Track G' },
{ name: 'Track H' },
{ name: 'Track I' }
]
},
{
id: '004', // generate id
name: 'Trance',
tracks: [
{ name: 'Track J' },
{ name: 'Track K' },
{ name: 'Track L' }
]
}
]
}
];
@danscotton
Copy link
Author

First stab at a solution:

data.reduce(function (collection, row) {
  var x = _.zipObject(['category', 'group', 'mix', 'track'], row);

  if (x.category) {
    collection.push({
      id: _.uniqueId('group'),
      name: x.group,
      category: x.category === 1 ? 'genre' : 'theme',
      mixes: []
    });
  }

  if (x.mix) {
    _.last(collection).mixes.push({
      id: _.uniqueId('mix'),
      name: x.mix,
      tracks: []
    });
  }

  if (x.track) {
    _.last(_.last(collection).mixes).tracks.push({
      name: x.track
    });
  }

  return collection;
}, []);

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