time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

unique.js (1855B)


      1 
      2 /**
      3 * @license Apache-2.0
      4 *
      5 * Copyright (c) 2021 The Stdlib Authors.
      6 *
      7 * Licensed under the Apache License, Version 2.0 (the "License");
      8 * you may not use this file except in compliance with the License.
      9 * You may obtain a copy of the License at
     10 *
     11 *    http://www.apache.org/licenses/LICENSE-2.0
     12 *
     13 * Unless required by applicable law or agreed to in writing, software
     14 * distributed under the License is distributed on an "AS IS" BASIS,
     15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     16 * See the License for the specific language governing permissions and
     17 * limitations under the License.
     18 */
     19 
     20 'use strict';
     21 
     22 // FUNCTIONS //
     23 
     24 /**
     25 * Comparator function to sort values in ascending order.
     26 *
     27 * @private
     28 * @param {number} a - first value
     29 * @param {number} b - second value
     30 * @returns {number} difference between `a` and `b`
     31 */
     32 function ascending( a, b ) {
     33 	return a - b;
     34 }
     35 
     36 
     37 // MAIN //
     38 
     39 /**
     40 * Removes duplicate values from a numeric array.
     41 *
     42 * @private
     43 * @param {NumberArray} arr - array to be deduped
     44 * @returns {NumberArray} deduped array
     45 */
     46 function unique( arr ) {
     47 	var len;
     48 	var val;
     49 	var i;
     50 	var j;
     51 
     52 	arr = arr.slice();
     53 	arr.sort( ascending );
     54 	len = arr.length;
     55 
     56 	// 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.
     57 	for ( i = 1, j = 0; i < len; i++ ) {
     58 		val = arr[ i ];
     59 		if ( arr[ j ] !== val ) {
     60 			j += 1;
     61 			arr[ j ] = val;
     62 		}
     63 	}
     64 	// Truncate the array:
     65 	arr.length = j + 1;
     66 	return arr;
     67 }
     68 
     69 
     70 // EXPORTS //
     71 
     72 module.exports = unique;