Last active
April 10, 2018 16:36
-
-
Save benhoIIand/ed7b5ef38a1a17f475b9830ded504d4b to your computer and use it in GitHub Desktop.
Mapping from one data structure to another
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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