1 /*jslint 2 white: true, 3 vars: true 4 */ 5 /*globals 6 module 7 */ 8 9 /** 10 * @fileOverview atropa-string-pad: Pads strings on the right or left with user 11 * defined characters or strings. 12 * @author <a href="mailto:matthewkastor@gmail.com"> 13 * Matthew Christopher Kastor-Inare III </a><br /> 14 * ☭ Hial Atropa!! ☭ 15 */ 16 17 /** 18 * Pads strings on the right or left with user defined characters or strings. 19 * @author <a href="mailto:matthewkastor@gmail.com"> 20 * Matthew Christopher Kastor-Inare III </a><br /> 21 * ☭ Hial Atropa!! ☭ 22 * @param {Number} length The desired length of the string. 23 * @param {String|Number} input The string or number to pad. 24 * @param {String} padding The string to use for padding, may be one or more 25 * characters. 26 * @param {Boolean} right set to true if you want to pad to the right. Defaults 27 * to left padding. 28 * @returns {String} Returns a string whose <code>length</code> is equal to the 29 * given length. 30 * @example 31 * console.log( 32 * pad(1, 'wee', 'um') 33 * ); 34 * // logs wee 35 * 36 * console.log( 37 * pad(1, 'wee', 'um', true) 38 * ); 39 * // logs wee 40 * 41 * console.log( 42 * pad(6, 'wee', 'um') 43 * ); 44 * // logs umuwee 45 * 46 * console.log( 47 * pad(6, 'wee', 'um', true) 48 * ); 49 * // logs weeumu 50 * 51 */ 52 function pad (length, input, padding, right) { 53 "use strict"; 54 length = parseInt(length, 10); 55 var i = String(input).split(''); 56 var p = String(padding).split(''); 57 58 if(i.length > length) { 59 return input; 60 } 61 62 while(i.length + p.length < length) { 63 p = p.concat(p); 64 } 65 66 while(i.length + p.length > length && p.length > 0 ) { 67 p.pop(); 68 } 69 70 if(right === true) { 71 i = i.concat(p); 72 } else { 73 i = p.concat(i); 74 } 75 76 return i.join(''); 77 } 78 79 try { 80 module.exports = pad; 81 } catch (ignore) { 82 // module.exports does not exist. 83 } 84 85 86 87