Skip to content

Instantly share code, notes, and snippets.

@shotah
Created July 5, 2023 18:01
Show Gist options
  • Save shotah/45e0812761e58c10f9a002405084d85b to your computer and use it in GitHub Desktop.
Save shotah/45e0812761e58c10f9a002405084d85b to your computer and use it in GitHub Desktop.
Typescript WIP
function fullJustify(words: string[], maxWidth: number): string[] {
let result: string[] = [];
let currentLineLength: number = 0;
let currentLineWords: string[] = [];
let currentSpaces: number = 0;
for (let i = 0; i < words.length; i++) {
currentLineWords.push(words[i]);
currentSpaces = currentLineWords.length - 1;
currentLineLength += words[i].length;
// Handles when we need to make a line
if (currentLineLength + currentSpaces + words[i + 1]?.length >= maxWidth) {
let missingSpaces = maxWidth - currentLineLength
let evenlySpacedSpaces = missingSpaces / (currentLineWords.length - 1);
// TODO: distribute odd spaces
let oddSpaces = missingSpaces % (currentLineWords.length - 1);
let joiner: string = ' '.repeat(evenlySpacedSpaces);
result.push(currentLineWords.join(joiner))
console.log(currentLineLength, currentSpaces, maxWidth, currentLineWords, missingSpaces, oddSpaces, `"${joiner}"`);
currentLineLength = 0;
currentLineWords = [];
currentSpaces = 0;
continue;
}
// Deal with the potenial last line:
if (words[i + 1] === undefined) {
let spacesToAdd = ' '.repeat(maxWidth - words[i].length)
result.push(words[i] + spacesToAdd);
}
}
return result;
};
let words: string[];
let maxWidth: number;
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
// Output:
// [
// "This is an",
// "example of text",
// "justification. "
// ]
console.log(fullJustify(words, maxWidth));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment