time-to-botec

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

order.js (1642B)


      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 // FUNCTIONS //
     22 
     23 /**
     24 * Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same.
     25 *
     26 * @private
     27 * @param {number} a - first number
     28 * @param {number} b - second number
     29 * @returns {boolean} comparison result
     30 */
     31 function compareFunction( a, b ) {
     32 	if ( a < b ) {
     33 		return -1;
     34 	}
     35 	if ( a > b ) {
     36 		return 1;
     37 	}
     38 	return 0;
     39 }
     40 
     41 
     42 // MAIN //
     43 
     44 /**
     45 * Returns a permutation which rearranges input array.
     46 *
     47 * @private
     48 * @param {ArrayLike} x - input array-like object
     49 * @returns {Array} permutation array
     50 */
     51 function order( x ) {
     52 	var arr;
     53 	var i;
     54 
     55 	arr = new Array( x.length );
     56 	for ( i = 0; i < x.length; i++ ) {
     57 		arr[ i ] = i;
     58 	}
     59 	return arr.sort( compare );
     60 
     61 	/**
     62 	* Compare the elements of the input array.
     63 	*
     64 	* @private
     65 	* @param {number} a - first number
     66 	* @param {number} b - second number
     67 	* @returns {boolean} comparison result
     68 	*/
     69 	function compare( a, b ) {
     70 		return compareFunction( x[a], x[b] );
     71 	}
     72 }
     73 
     74 
     75 // EXPORTS //
     76 
     77 module.exports = order;