order.js (2246B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 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 // MODULES // 22 23 var Int32Array = require( '@stdlib/array/int32' ); 24 25 26 // FUNCTIONS // 27 28 /** 29 * Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same. 30 * 31 * @private 32 * @param {number} a - first number 33 * @param {number} b - second number 34 * @returns {boolean} comparison result 35 */ 36 function ascending( a, b ) { 37 if ( a < b ) { 38 return -1; 39 } 40 if ( a > b ) { 41 return 1; 42 } 43 return 0; 44 } 45 46 /** 47 * Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same. 48 * 49 * @private 50 * @param {number} a - first number 51 * @param {number} b - second number 52 * @returns {boolean} comparison result 53 */ 54 function descending( a, b ) { 55 if ( a < b ) { 56 return 1; 57 } 58 if ( a > b ) { 59 return -1; 60 } 61 return 0; 62 } 63 64 65 // MAIN // 66 67 /** 68 * Returns a permutation which rearranges input array. 69 * 70 * @private 71 * @param {ArrayLike} x - input array-like object 72 * @param {boolean} invert - controls whether to permutation that sorts input array in descending order 73 * @returns {Array} permutation array 74 */ 75 function order( x, invert ) { 76 var comparator; 77 var arr; 78 var i; 79 80 comparator = ( invert ) ? descending : ascending; 81 arr = new Int32Array( x.length ); 82 for ( i = 0; i < x.length; i++ ) { 83 arr[ i ] = i; 84 } 85 return arr.sort( compare ); 86 87 /** 88 * Compare the elements of the input array. 89 * 90 * @private 91 * @param {number} a - first number 92 * @param {number} b - second number 93 * @returns {boolean} comparison result 94 */ 95 function compare( a, b ) { 96 return comparator( x[a], x[b] ); 97 } 98 } 99 100 101 // EXPORTS // 102 103 module.exports = order;