whisper.cat/weboasis/text/js/lib/justified.js
2023-10-05 23:28:32 +11:00

7 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*!
* justified <https://github.com/jonschlinkert/justified>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/
function repeat(n,e){if("string"!=typeof n)throw new TypeError("expected a string");if(1===e)return n;if(2===e)return n+n;var t=n.length*e;if(cache!==n||"undefined"==typeof cache)cache=n,res="";else if(res.length>=t)return res.substr(0,t);for(;t>res.length&&e>1;)1&e&&(res+=n),e>>=1,n+=n;return res+=n,res=res.substr(0,t),res}function longest(n){if(!Array.isArray(n))throw new TypeError("expected an array");var e=n.length;if(0!==e){var t=n[0];"number"==typeof t&&(t=String(t));for(var r=t.length,a=0;++a<e;){var i=n[a];if(null!=i){"number"==typeof i&&(i=String(i));var o=i.length;"number"==typeof o&&o>r&&(r=o,t=i)}}return t}}function wrap(n,e){if(null==n)return n;var t=(e=e||{}).width||50,r="string"==typeof e.indent?e.indent:" ",a=e.newline||"\n"+r,i="function"==typeof e.escape?e.escape:identity,o=".{1,"+t+"}";!0!==e.cut&&(o+="([\\s]+|$)|[^\\s]+?([\\s]+|$)");var s=new RegExp(o,"g"),f=r+(n.match(s)||[]).map(function(n){return"\n"===n.slice(-1)&&(n=n.slice(0,n.length-1)),i(n)}).join(a);return!0===e.trim&&(f=f.replace(/[ \t]*$/gm,"")),f}function identity(n){return n}var lastRandomIndex=0;function justify(n,e){var t=Object.assign({random:random,width:55},e);lastRandomIndex=0,n=wrap(n,t);for(var r=t.indent?repeat(" ",t.indent):"",a=n.split(/\r?\n/),i=longest(a).length,o=Math.min(t.width,i),s=a.length,f="",u=0;u<s;u++){var l=a[u].trim(),d=u!==s-1||!0===t.justifyLastLine;u===s-1&&"function"==typeof t.justifyLastLine&&(d=t.justifyLastLine(l,o)),d&&(l=toMaxLength(l,o,t)),f+=r+l+"\n"}return f}function toMaxLength(n,e,t){for(var r=e-n.length,a=n.split(" "),i=a.length;r-- >0;)a[t.random(i-2)]+=" ";return a.join(" ").trim()}function random(n){var e=[.14975434898516649,.48920102670502064,.5460856891554375,.843156677246687,.5339584048702419,.6557222579529927,.025277961886063904,.7906919328816282,.39547316726978843,.8046447313481258,.40539968121122616,.3240593946801942,.04700841115323562],t=e[lastRandomIndex%e.length];return lastRandomIndex>1e3?lastRandomIndex=0:lastRandomIndex++,Math.floor(t*(n+1))}