Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const _ = require( 'lodash' );
- const mixins = {
- /**
- * Return a new array containing only the unique objects inside the provided
- * array. Unlike _.uniq, this will check _every_ key/value in the array
- *
- * @param {Array} arr Array of structurally identical objects
- * @return {Array}
- * @example
- *
- * const objs = [ { x: 1, y: 2 }, { a: 1, b: 2 }, { x: 1, y: 2 }];
- *
- * console.log( _( objs ).uniqObjs().value() )
- * console.log( _.uniqObjs( objs ) )
- *
- * // => [ { x: 1, y: 2 }, { a: 1, b: 2 } ]
- */
- uniqObjs: arr => {
- // Make sure that the arr parameter is a defined & populated array of objects
- if( _.isUndefined( arr ) || ! _.isArray( arr ) || ! arr.length || ! _.isObject( arr[0] ) )
- return false;
- const uniqs = [];
- // Filter out the duplicate objects within the array by checking if
- // the stringified object value already exist in the temporary uniqs
- // array (while adding them to the variable)
- return _.filter( arr, ( obj ) => {
- // Use _.sortObj to sort the contents of the object by the keys, since stringify
- // will use the current order (which means identical objects in different orders
- // will be seen as discrepancies)
- if( _.indexOf( uniqs, JSON.stringify( mixins.sortObj( obj ) ) ) === -1 ){
- uniqs.push( JSON.stringify( mixins.sortObj( obj ) ) );
- return true;
- }
- return false;
- });
- },
- /**
- * Return a copy of the object with the content sorted by the keys
- *
- * @param {Object} obj Object to sort by keys
- * @param {Function} comparator Function to compare/sort the elements
- * @return {Object}
- * @example
- *
- * const obj = {b: 3, c: 2, a: 1};
- *
- * console.log( _.sortObj( obj ) );
- * console.log( _( obj ).sortObj().value() );
- *
- * // => {a: 1, b: 3, c: 2}
- *
- * _.sortObj(obj, (value, key) => {
- * return value;
- * });
- *
- * // => {a: 1, c: 2, b: 3}
- *
- *
- */
- sortObj: ( obj, comparator ) => {
- const keys = _.sortBy( _.keys( obj ), key => {
- return _.isFunction( comparator ) ? comparator(obj[key], key) : key;
- });
- return _.object(keys, _.map(keys, key => {
- return obj[key];
- }));
- }
- };
- _.mixin( mixins );
- module.exports = _;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement