diff --git a/src/index.js b/src/index.js index c80614d2..b2c6bd85 100644 --- a/src/index.js +++ b/src/index.js @@ -71,6 +71,7 @@ import occurrences from './occurrences' import getMiddle from './getMiddle' import debounce from './debounce' import curry from './curry' +import textJustification from './textJustification' import removeProperty from './removeProperty' export { @@ -147,5 +148,6 @@ export { getMiddle, debounce, curry, + textJustification, removeProperty, } diff --git a/src/textJustification.js b/src/textJustification.js new file mode 100644 index 00000000..fd9f9710 --- /dev/null +++ b/src/textJustification.js @@ -0,0 +1,74 @@ +export default textJustification + +/** + * + * Original Source: https://www.malikbrowne.com/blog/text-justification-coding-question + * + * Description: Given an array of words(input) and a length L, format the text such that each + * line has exactly L characters and is fully (left and right) justified. + * + * @param {Array} input - String array to be justified + * @param {Integer} L - Length of characters per line + * @return {Array} output - The string fully justified + */ + +function textJustification(input, L) { + let index = 0 + const output = [] + + while (index < input.length) { + + let count = input[index].length + let last = index + 1 + + while (last < input.length) { + + if (input[last].length + count + 1 > L) { + break + } + count += input[last].length + 1 + last++ + } + + let line = '' + const diff = last - index - 1 + + if (last === input.length || diff === 0) { + + for (let i = index; i < last; i++) { + + line += `${input[i]} ` + } + + line = line.substr(0, line.length - 1) + + for (let i = line.length; i < L; i++) { + line += ' ' + } + + } else { + + const space = (L - count) / diff + const remainder = (L - count) % diff + + for (let i = index; i < last; i++) { + line += input[i] + + if (i < last - 1) { + + const max = space + ((i - index) < remainder ? 1 : 0) + + for (let j = 0; j <= max; j++) { + line += ' ' + } + } + } + } + + output.push(line) + index = last + } + return output +} + +/* eslint complexity: "off", max-depth: "off" */ diff --git a/test/textJustification.test.js b/test/textJustification.test.js new file mode 100644 index 00000000..9602e926 --- /dev/null +++ b/test/textJustification.test.js @@ -0,0 +1,10 @@ +import test from 'ava' +import {textJustification} from '../src' + +test('Text justification function', t => { + const object = ['This','is','an','example','of','text','justification.'] + const len = 16 + const expected = ['This is an','example of text','justification. '] + const actual = textJustification(object, len) + t.deepEqual(actual, expected) +}) \ No newline at end of file