time-to-botec

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

zero_pad.js (1795B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2022 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 * Tests if a string starts with a minus sign (`-`).
     25 *
     26 * @private
     27 * @param {string} str - input string
     28 * @returns {boolean} boolean indicating if a string starts with a minus sign (`-`)
     29 */
     30 function startsWithMinus( str ) {
     31 	return str[ 0 ] === '-';
     32 }
     33 
     34 /**
     35 * Returns a string of `n` zeros.
     36 *
     37 * @private
     38 * @param {number} n - number of zeros
     39 * @returns {string} string of zeros
     40 */
     41 function zeros( n ) {
     42 	var out = '';
     43 	var i;
     44 	for ( i = 0; i < n; i++ ) {
     45 		out += '0';
     46 	}
     47 	return out;
     48 }
     49 
     50 
     51 // MAIN //
     52 
     53 /**
     54 * Pads a token with zeros to the specified width.
     55 *
     56 * @private
     57 * @param {string} str - token argument
     58 * @param {number} width - token width
     59 * @param {boolean} [right=false] - boolean indicating whether to pad to the right
     60 * @returns {string} padded token argument
     61 */
     62 function zeroPad( str, width, right ) {
     63 	var negative = false;
     64 	var pad = width - str.length;
     65 	if ( pad < 0 ) {
     66 		return str;
     67 	}
     68 	if ( startsWithMinus( str ) ) {
     69 		negative = true;
     70 		str = str.substr( 1 );
     71 	}
     72 	str = ( right ) ?
     73 		str + zeros( pad ) :
     74 		zeros( pad ) + str;
     75 	if ( negative ) {
     76 		str = '-' + str;
     77 	}
     78 	return str;
     79 }
     80 
     81 
     82 // EXPORTS //
     83 
     84 module.exports = zeroPad;