utils/string.js

import _ from 'lodash';

/**
 * Utilities for working with strings.
 * @module StringUtils
 */
const StringUtils = {
    /**
     * Removes spaces from the provided string.
     * @static
     * @function removeSpaces
     * @param {String} str - The string to remove spaces from.
     * @example
     * StringUtils.removeSpaces('Foo Bar'); // 'FooBar'
     * @returns {String} - The string with no spaces.
     */
    removeSpaces(str) {
        if (!_.isString(str)) {
            throw new Error('You can only remove spaces from a string.');
        }

        return str.replace(/\s+/g, '');
    },

    /**
     * Pads a number with a leading zero if necessary and returns it as a string representation.
     * @static
     * @function pad
     * @param {Number} num - The number to pad.
     * @example
     * StringUtils.pad(1);
     * @returns {String} - The padded number.
     */
    pad(num) {
        if (!_.isNumber(num)) {
            throw new Error('You can only pad numbers.');
        }

        return (num < 10) ? `0${num}` : `${num}`;
    }
};

export default StringUtils;