Skip to content

Instantly share code, notes, and snippets.

@e-mihaylin
Created October 17, 2018 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e-mihaylin/9c0291bc21600ea813f6795e91d11c6e to your computer and use it in GitHub Desktop.
Save e-mihaylin/9c0291bc21600ea813f6795e91d11c6e to your computer and use it in GitHub Desktop.
const justify = (s, length) => {
s = s.replace(/\n/g, ' ')
s = s.split` `;
const res = [];
let line = [];
let words = 0;
for (let i = 0; i < s.length; i++) {
if (words + line.length - 1 + s[i].length < length) {
line.push(s[i]);
words += s[i].length;
} else {
const spaces = [];
for (let j = 0; j < line.length - 1; j++) spaces.push` `;
for (let j = 0; j < length - words - line.length + 1; j++)
spaces[j % (line.length - 1)] += ' ';
let l = '';
for (let j = 0; j < line.length; j++) {
if (j > 0) l += spaces[j - 1];
l += line[j];
}
res.push(l);
line = [];
words = 0;
i -= 1;
}
}
if (line.length > 0) res.push(line.join` `);
return res.join`\n`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment