jLinux

Untitled

Dec 26th, 2015
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2. const _ = require( 'lodash' );
  3.  
  4. const mixins = {
  5.  
  6.     /**
  7.      * Return a new array containing only the unique objects inside the provided
  8.      * array. Unlike _.uniq, this will check _every_ key/value in the array
  9.      *
  10.      * @param   {Array}     arr     Array of structurally identical objects
  11.      * @return  {Array}
  12.      * @example
  13.      *
  14.      * const objs = [ { x: 1, y: 2 }, { a: 1, b: 2 }, { x: 1, y: 2 }];
  15.      *
  16.      * console.log( _( objs ).uniqObjs().value() )
  17.      * console.log( _.uniqObjs( objs ) )
  18.      *
  19.      * // => [ { x: 1, y: 2 }, { a: 1, b: 2 } ]
  20.      */
  21.     uniqObjs: arr => {
  22.         // Make sure that the arr parameter is a defined & populated array of objects
  23.         if( _.isUndefined( arr ) || ! _.isArray( arr ) || ! arr.length || ! _.isObject( arr[0] ) )
  24.             return false;
  25.  
  26.         const uniqs = [];
  27.  
  28.         // Filter out the duplicate objects within the array by checking if
  29.         // the stringified object value already exist in the temporary uniqs
  30.         // array (while adding them to the variable)
  31.         return _.filter( arr, ( obj ) => {
  32.             // Use _.sortObj to sort the contents of the object by the keys, since stringify
  33.             // will use the current order (which means identical objects in different orders
  34.             // will be seen as discrepancies)
  35.             if( _.indexOf( uniqs, JSON.stringify( mixins.sortObj( obj ) ) ) === -1 ){
  36.                 uniqs.push( JSON.stringify( mixins.sortObj( obj ) ) );
  37.                 return true;
  38.             }
  39.  
  40.             return false;
  41.         });
  42.     },
  43.  
  44.     /**
  45.      * Return a copy of the object with the content sorted by the keys
  46.      *
  47.      * @param   {Object}     obj     Object to sort by keys
  48.      * @return  {Object}
  49.      * @example
  50.      *
  51.      * const obj = {c:1, b:2, a:3};
  52.      *
  53.      * console.log( _.sortObj( obj ) );
  54.      * console.log( _( obj ).sortObj().value() );
  55.      *
  56.      * // => { a: 3, b: 2, c: 1 }
  57.      */
  58.     sortObj: obj => {
  59.         const result = {};
  60.  
  61.         _( obj ).
  62.             keys( )
  63.             .sort()
  64.             .forEach( ( v, i ) => {
  65.                 result[ v ] = obj[ v ];
  66.             })
  67.             .commit();
  68.  
  69.         return result;
  70.     }
  71. };
  72.  
  73. _.mixin( mixins );
  74.  
  75. module.exports = _;
Advertisement
Add Comment
Please, Sign In to add comment