Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- http://pastebin.com/H6upTAAr'use strict';
- const _ = require( 'lodash' );
- const lodash = _.runInContext();
- 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( ! lodash.isArray( arr ) || ! arr.length || ! lodash.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 lodash.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( lodash.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 = lodash.sortBy( lodash.keys( obj ), key => {
- return lodash.isFunction( comparator ) ? comparator( obj[ key ], key ) : key;
- });
- return lodash.object( keys, lodash.map( keys, key => {
- return obj[ key ];
- }));
- },
- /**
- * Check if the provided number is a float or integer value. This just tacks
- * a 2nd check onto lodashes isNumber, which uses a lenient comparative operator
- * to check if the value of parseFloat is the same as the provided number
- *
- * @param {String|Integer|Number} num Number to check
- * @return {Boolean}
- * @example
- *
- * _.isNumber( 123 )
- * _.isNumber( '123' )
- * _.isNumber( 1.2 )
- * _.isNumber( '1.2' )
- *
- * // => true
- *
- */
- isNumber: ( num ) => {
- return lodash.isNumber( num ) || parseFloat( num ) == num;
- }
- };
- _.mixin( mixins );
- module.exports = _;
Advertisement
Add Comment
Please, Sign In to add comment