Search code examples
javascriptjavascript-objects

Using map/ for Each to resolve a web socket message


I have a working solution that looks like this.

 resolve(stats) {
    object.keys(stats).forEach( key => {
       switch (true) {
         case key === 'PhoneNumber':
             Store.render('tel Number', { PhoneNumber });
             break;
         case key === 'Location':
             getLocation();
             break;
         case key === 'Status':
             getStatus(Status);
             break;
         default:
             break;
     }
 });
}

but using switch is messy(?) and it introduces additional cyclomatic complexity. When I try to rewrite it using object literal i just get e huge amount of errors and it just stops working. Currently I'm trying to make it work using variant below,but i still get a mass of errors,because it tries to run every function even though there's no such key present

  resolve(stats) {
    object.keys(stats).forEach( key => {
       const keyValue = {
             PhoneNumber: Store.render('tel Number', { PhoneNumber }),
             Location: getLocation(),
             Status: getStatus(Status)
             default: null,
       } 
       return keyValue[key] || keyValue.default;
     })
   }     

Edit: maybe i need to use array.prototype.reduce? or employ array.some inside the function?


Solution

  • What you want is to wrap those values into a function like so:

    // Dummy function
    function getLocation() {
      return '0,0';
    }
    // Dummy function
    function getStatus( status ) {
      return `is: ${ status }`;
    }
    
    // Dummy stats
    const stats = {
      PhoneNumber: '0012345',
      Location: 'foo',
      Status: 'online',
      SomeOtherStat: 'bar',
    };
    
    const mapper = {
      PhoneNumber: ( data ) => {
        //Store.render( data ),
        return data;
      },
      Location: () => getLocation(),
      Status: ( data ) => getStatus( data ),
    };
    
    function resolve( stats ) {
      const keys = Object.keys( stats );
      const result = Object.keys( stats ).map( ( key ) => (
        // Check if mapper is available
        mapper[ key ]
          // Run mapper and pass the current value
          ? mapper[ key ]( stats[ key ] )
          // Otherwise return null
          : null
      ) );
      console.log( result );
    }
    
    resolve(stats);

    Otherwise the browser tries to execute it as soon as you create the keyValue variable.

    Also, you can declare your resolver object outside