Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Test
  2.  
  3. const test = require('ava');
  4. const reduce = require('./reduce');
  5.  
  6. test('Can groupBy', (t) => {
  7.   const input = [
  8.     {
  9.       "type": "hotel",
  10.       "name": "Intercontinental"
  11.     },
  12.     {
  13.       "type": "airport",
  14.       "name": "Heathrow"
  15.     },
  16.     {
  17.       "type": "hotel",
  18.       "name": "Hilton"
  19.     },
  20.     {
  21.       "type": "station",
  22.       "name": "King's Cross"
  23.     },
  24.     {
  25.       "type": "airport",
  26.       "name": "Stansted"
  27.     }
  28.   ];
  29.  
  30.   const expected = {
  31.     airport: ['Heathrow', 'Stansted'],
  32.     station: "King's Cross",
  33.     hotel: ['Intercontinental', 'Hilton']
  34.   }
  35.  
  36.   const reduced = reduce(input);
  37.  
  38.   t.deepEqual(expected, reduced);
  39. });
  40.  
  41.  
  42. // Solution
  43.  
  44. const reduce = (input) => {
  45.   const result = input.reduce((collection, element) => {
  46.     const current = collection[element.type]
  47.     if(current && Array.isArray(current)) {
  48.       collection[element.type].push(element.name);
  49.     } else if(current) {
  50.       collection[element.type] = [current, element.name]
  51.     } else {
  52.       collection[element.type] = element.name
  53.     }
  54.     return collection;
  55.   }, {})
  56.   return result;
  57. };
  58.  
  59. module.exports = reduce;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement