mirror of https://github.com/lukechilds/node.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.3 KiB
48 lines
1.3 KiB
9 years ago
|
var createPadding = require('./_createPadding'),
|
||
|
stringSize = require('./_stringSize'),
|
||
|
toInteger = require('./toInteger'),
|
||
|
toString = require('./toString');
|
||
10 years ago
|
|
||
9 years ago
|
/* Built-in method references for those with the same name as other `lodash` methods. */
|
||
9 years ago
|
var nativeCeil = Math.ceil,
|
||
9 years ago
|
nativeFloor = Math.floor;
|
||
10 years ago
|
|
||
|
/**
|
||
|
* Pads `string` on the left and right sides if it's shorter than `length`.
|
||
|
* Padding characters are truncated if they can't be evenly divided by `length`.
|
||
|
*
|
||
|
* @static
|
||
|
* @memberOf _
|
||
|
* @category String
|
||
|
* @param {string} [string=''] The string to pad.
|
||
|
* @param {number} [length=0] The padding length.
|
||
|
* @param {string} [chars=' '] The string used as padding.
|
||
|
* @returns {string} Returns the padded string.
|
||
|
* @example
|
||
|
*
|
||
|
* _.pad('abc', 8);
|
||
|
* // => ' abc '
|
||
|
*
|
||
|
* _.pad('abc', 8, '_-');
|
||
|
* // => '_-abc_-_'
|
||
|
*
|
||
|
* _.pad('abc', 3);
|
||
|
* // => 'abc'
|
||
|
*/
|
||
|
function pad(string, length, chars) {
|
||
9 years ago
|
string = toString(string);
|
||
|
length = toInteger(length);
|
||
10 years ago
|
|
||
9 years ago
|
var strLength = stringSize(string);
|
||
|
if (!length || strLength >= length) {
|
||
10 years ago
|
return string;
|
||
|
}
|
||
|
var mid = (length - strLength) / 2,
|
||
9 years ago
|
leftLength = nativeFloor(mid),
|
||
|
rightLength = nativeCeil(mid);
|
||
10 years ago
|
|
||
9 years ago
|
return createPadding('', leftLength, chars) + string + createPadding('', rightLength, chars);
|
||
10 years ago
|
}
|
||
|
|
||
|
module.exports = pad;
|