Skip to content

Instantly share code, notes, and snippets.

@Minasokoni
Last active February 26, 2021 16:14
Show Gist options
  • Save Minasokoni/1871b82a8591bc3bc150c9601c6d0e90 to your computer and use it in GitHub Desktop.
Save Minasokoni/1871b82a8591bc3bc150c9601c6d0e90 to your computer and use it in GitHub Desktop.
Telegram Exercise
function compareArray(a, b) {
// check if arrays, check length, check index match
return Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((val, index) => val === b[index]);
}
function wrapText(words, maxLength) {
const result = [];
let row = [];
// iterate through each word
words.forEach(word => {
// check length, if > maxLength add row and reset
if (row.join(' ').length + word.length >= maxLength) {
result.push(row.join(' '));
// add word into array
row = [word];
} else {
// add word to row if < maxLength
row.push(word);
}
});
// once row length is > 0
if (row.length > 0) {
result.push(row.join(' '));
}
return result;
}
// output
function runTestCase({words, maxLength, expected}) {
const result = wrapText(words, maxLength)
const compare = compareArray(result, expected)
// didn't know this existed :D
console.assert(compare, 'AssertionError')
console.log('test case result:', compare ? result : [])
}
// My fake Test Case
const testCases = [
{
words: [
"The",
"task",
"is",
"to",
"write",
"a",
"program",
"which",
"accepts",
"lines",
"of",
"text",
"and",
"generates",
"output",
"lines",
"of",
"a",
"different",
"length,",
"without",
"splitting",
"any",
"of",
"the",
"words",
"in",
"the",
"text.",
"We",
"assume",
"no",
"word",
"is",
"longer",
"than",
"the",
"size",
"of",
"the",
"output",
"lines.",
],
maxLength: 40,
expected: [
"The task is to write a program which",
"accepts lines of text and generates",
"output lines of a different length,",
"without splitting any of the words in",
"the text. We assume no word is longer",
"than the size of the output lines.",
]
},
{
words: [
"The",
"Pacific",
"Ocean",
"is",
"the",
"largest",
"and",
"deepest",
"of",
"Earth's",
"oceanic",
"divisions.",
"It",
"extends",
"from",
"the",
"Arctic",
"Ocean",
"in",
"the",
"north",
"to",
"the",
"Southern",
"Ocean",
"in",
"the",
"south.",
],
maxLength: 11,
expected: [
"The Pacific",
"Ocean is",
"the largest",
"and deepest",
"of Earth's",
"oceanic",
"divisions.",
"It extends",
"from the",
"Arctic",
"Ocean in",
"the north",
"to the",
"Southern",
"Ocean in",
"the south.",
]
}
]
// Run test cases
testCases.forEach(({words, maxLength, expected}) => runTestCase({words, maxLength, expected}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment