Last change
on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.4 KB
|
Rev | Line | |
---|
[6a3a178] | 1 | 'use strict'
|
---|
| 2 | var stringWidth = require('string-width')
|
---|
| 3 |
|
---|
| 4 | exports.center = alignCenter
|
---|
| 5 | exports.left = alignLeft
|
---|
| 6 | exports.right = alignRight
|
---|
| 7 |
|
---|
| 8 | // lodash's way of generating pad characters.
|
---|
| 9 |
|
---|
| 10 | function createPadding (width) {
|
---|
| 11 | var result = ''
|
---|
| 12 | var string = ' '
|
---|
| 13 | var n = width
|
---|
| 14 | do {
|
---|
| 15 | if (n % 2) {
|
---|
| 16 | result += string;
|
---|
| 17 | }
|
---|
| 18 | n = Math.floor(n / 2);
|
---|
| 19 | string += string;
|
---|
| 20 | } while (n);
|
---|
| 21 |
|
---|
| 22 | return result;
|
---|
| 23 | }
|
---|
| 24 |
|
---|
| 25 | function alignLeft (str, width) {
|
---|
| 26 | var trimmed = str.trimRight()
|
---|
| 27 | if (trimmed.length === 0 && str.length >= width) return str
|
---|
| 28 | var padding = ''
|
---|
| 29 | var strWidth = stringWidth(trimmed)
|
---|
| 30 |
|
---|
| 31 | if (strWidth < width) {
|
---|
| 32 | padding = createPadding(width - strWidth)
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | return trimmed + padding
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | function alignRight (str, width) {
|
---|
| 39 | var trimmed = str.trimLeft()
|
---|
| 40 | if (trimmed.length === 0 && str.length >= width) return str
|
---|
| 41 | var padding = ''
|
---|
| 42 | var strWidth = stringWidth(trimmed)
|
---|
| 43 |
|
---|
| 44 | if (strWidth < width) {
|
---|
| 45 | padding = createPadding(width - strWidth)
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | return padding + trimmed
|
---|
| 49 | }
|
---|
| 50 |
|
---|
| 51 | function alignCenter (str, width) {
|
---|
| 52 | var trimmed = str.trim()
|
---|
| 53 | if (trimmed.length === 0 && str.length >= width) return str
|
---|
| 54 | var padLeft = ''
|
---|
| 55 | var padRight = ''
|
---|
| 56 | var strWidth = stringWidth(trimmed)
|
---|
| 57 |
|
---|
| 58 | if (strWidth < width) {
|
---|
| 59 | var padLeftBy = parseInt((width - strWidth) / 2, 10)
|
---|
| 60 | padLeft = createPadding(padLeftBy)
|
---|
| 61 | padRight = createPadding(width - (strWidth + padLeftBy))
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | return padLeft + trimmed + padRight
|
---|
| 65 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.