Skip to content

Instantly share code, notes, and snippets.

@benhoIIand
Last active April 10, 2018 16:36
Show Gist options
  • Save benhoIIand/ed7b5ef38a1a17f475b9830ded504d4b to your computer and use it in GitHub Desktop.
Save benhoIIand/ed7b5ef38a1a17f475b9830ded504d4b to your computer and use it in GitHub Desktop.
Mapping from one data structure to another
function process (input) {
// Reduce over input to process an object where the key is the location and the value is the products
const tree = input
.reduce((output, o) => {
o.locations.forEach(location => {
if (output[location] === undefined) {
output[location] = [];
}
output[location].push(o.name);
});
return output;
}, {});
// Format the tree into an array of objects
const output = [];
for(const location in tree) {
if (tree.hasOwnProperty(location)) {
output.push({ location, names: tree[location] });
}
}
return output;
};
module.exports = process;
const process = require('./process');
describe('Converting an array of products and their locations', () => {
test('returns an array of location objects', () => {
const input = [
{ name: 'Product 1', locations: ['Paris', 'France', 'Europe'] },
{ name: 'Product 2', locations: ['Bordeux', 'France', 'Europe'] },
{ name: 'Product 3', locations: ['Edinburgh', 'Scotland', 'Europe'] },
];
// Output
const expectedOutput = [
{
location: 'Paris',
names: ['Product 1'],
},
{
location: 'Bordeux',
names: ['Product 2'],
},
{
location: 'Edinburgh',
names: ['Product 3'],
},
{
location: 'Scotland',
names: ['Product 3'],
},
{
location: 'France',
names: ['Product 1', 'Product 2'],
},
{
location: 'Europe',
names: ['Product 1', 'Product 2', 'Product 3'],
}
];
expect(process(input)).toEqual(output);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment