/** * @license Apache-2.0 * * Copyright (c) 2022 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'; // FUNCTIONS // /** * Tests if a string starts with a minus sign (`-`). * * @private * @param {string} str - input string * @returns {boolean} boolean indicating if a string starts with a minus sign (`-`) */ function startsWithMinus( str ) { return str[ 0 ] === '-'; } /** * Returns a string of `n` zeros. * * @private * @param {number} n - number of zeros * @returns {string} string of zeros */ function zeros( n ) { var out = ''; var i; for ( i = 0; i < n; i++ ) { out += '0'; } return out; } // MAIN // /** * Pads a token with zeros to the specified width. * * @private * @param {string} str - token argument * @param {number} width - token width * @param {boolean} [right=false] - boolean indicating whether to pad to the right * @returns {string} padded token argument */ function zeroPad( str, width, right ) { var negative = false; var pad = width - str.length; if ( pad < 0 ) { return str; } if ( startsWithMinus( str ) ) { negative = true; str = str.substr( 1 ); } str = ( right ) ? str + zeros( pad ) : zeros( pad ) + str; if ( negative ) { str = '-' + str; } return str; } // EXPORTS // module.exports = zeroPad;