unique.js (2172B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // VARIABLES // 22 23 var SORT_OPTS = { 24 'numeric': true // Use numeric collation such that "1" < "2" < "10"... 25 }; 26 27 28 // FUNCTIONS // 29 30 /** 31 * Comparator function to sort values in ascending order. 32 * 33 * @private 34 * @param {*} a - first value 35 * @param {*} b - second value 36 * @returns {number} negative number if `a` comes before `b, positive if `a` comes after `b`, and `0` if they are equivalent 37 */ 38 function ascending( a, b ) { 39 return String( a ).localeCompare( String( b ), void 0, SORT_OPTS ); 40 } 41 42 43 // MAIN // 44 45 /** 46 * Returns the unique elements in an array. 47 * 48 * @private 49 * @param {Array} arr - input array 50 * @returns {Array} array of unique elements 51 */ 52 function unique( arr ) { 53 var len; 54 var out; 55 var val; 56 var i; 57 var j; 58 59 // Copy the array to avoid mutation: 60 out = Array.prototype.slice.call( arr ); 61 len = out.length; 62 63 // Sort array in ascending order: 64 out.sort( ascending ); 65 66 // Loop through the array, only incrementing a pointer when successive values are different. When a succeeding value is different, move the pointer and set the next value. In the trivial case where all array elements are unique, we incur a slight penalty in resetting the element value for each unique value. In other cases, we simply move a unique value to a new position in the array. The end result is a sorted array with unique values. 67 for ( i = 1, j = 0; i < len; i++ ) { 68 val = out[ i ]; 69 if ( out[ j ] !== val ) { 70 j += 1; 71 out[ j ] = val; 72 } 73 } 74 // Truncate the array: 75 out.length = j+1; 76 return out; 77 } 78 79 80 // EXPORTS // 81 82 module.exports = unique;