Per a Reddit Daily Programming Challenge, I am performing a matrix transposition on a string using JavaScript.
Example input: 'The quick brown fox jumped over the lazy dog'
Output:
Tqbfjotld hurouvhao eioxmeezg cw pr y kn e d
While my code works, I wanted to know:
- From a readability standpoint, would it be better to break the code up into smaller functions?
- If there's anything in the code that can be simplified.
transposeString('The quick brown fox jumped over the lazy dog');
function transposeString(str) {
if (str.indexOf(' ') === -1) {
var map = Array.prototype.map;
var output = map.call(str, function (char) {
return char + '\n';
});
return output.join('');
} else {
var master = [],
longestWord = '';
words = str.split(' ');
words.forEach(function(word) {
if (word.length >= longestWord.length) longestWord = word;
});
longestWord.split('').forEach(function() {
master.push([]);
});
var treatedWords = words.map(function (word) {
if (word.length < longestWord.length) {
var spaces = Array(longestWord.length - word.length + 1).join(' ');
return word = word + spaces;
} else {
return word;
}
});
treatedWords.forEach(function (word) {
var n = 0;
word.split('').forEach(function (char) {
master[n].push(char);
n++;
});
});
master.forEach(function (arr) {
console.log(arr.join(''));
});
return;
}
}