UNPKG

@technobuddha/library

Version:
91 lines (90 loc) 3.52 kB
"use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.wordwrap = void 0; var constants_1 = require("../constants"); var splitWords_1 = __importDefault(require("../splitWords")); /** * Wrap text so that it fits within a area of fixed width * * @param input the text to wrap * @param options * @default width 75 * @default separator \n * @default cut default false * @default trailingSpaces false * @returns wrapped text */ function wordwrap(input, _a) { var e_1, _b; var _c = _a === void 0 ? {} : _a, _d = _c.width, width = _d === void 0 ? 75 : _d, _e = _c.separator, separator = _e === void 0 ? '\n' : _e, _f = _c.cut, cut = _f === void 0 ? false : _f, _g = _c.trailingSpaces, trailingSpaces = _g === void 0 ? false : _g; if (width <= 0) { return input; } else if (cut) { var result_1 = constants_1.empty; // walk through each character and add separators where appropriate for (var i = 0; i < input.length; ++i) { if (i % width === 0 && i > 0) result_1 += separator; result_1 += input.charAt(i); } // fill the rest of the line with spaces if trailingSpaces option is true if (trailingSpaces) result_1 += constants_1.space.repeat(width - input.length % width); return result_1; } var currentColumn = 0; var result = constants_1.empty; try { for (var _h = __values(splitWords_1.default(input)), _j = _h.next(); !_j.done; _j = _h.next()) { var word = _j.value; // if adding a space and the next word would cause this line to be longer than width... if (word.length + currentColumn > width) { if (trailingSpaces) { // fill the rest of the line with spaces if trailingSpaces option is true result += constants_1.space.repeat(width - currentColumn); } //start new line result += separator; currentColumn = 0; } // if not at the begining of the line, add a space in front of the word if (currentColumn > 0) { result += constants_1.space; currentColumn++; } // tack on the next word, update current column, a pop words array result += word; currentColumn += word.length; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_j && !_j.done && (_b = _h.return)) _b.call(_h); } finally { if (e_1) throw e_1.error; } } // fill the rest of the line with spaces if trailingSpaces option is true if (trailingSpaces) { while (currentColumn++ < width) result += constants_1.space; } return result; } exports.wordwrap = wordwrap; exports.default = wordwrap;