All files / anova1/lib unique.js

64.63% Statements 53/82
100% Branches 1/1
0% Functions 0/2
64.63% Lines 53/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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

	// Copy the array to avoid mutation:
	out = Array.prototype.slice.call( arr );
	len = out.length;

	// Sort array in ascending order:
	out.sort( ascending );

	// 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.
	for ( i = 1, j = 0; i < len; i++ ) {
		val = out[ i ];
		if ( out[ j ] !== val ) {
			j += 1;
			out[ j ] = val;
		}
	}
	// Truncate the array:
	out.length = j+1;
	return out;
}
 
 
// EXPORTS //
 
module.exports = unique;