function makeTable(data) {
data = data.join('').split('');
let width = Math.sqrt(data.length) | 0;
let height = (data.length / width) | 0;
while (width * height !== data.length) {
width--;
height = (data.length / width) | 0;
}
const position = [ 0, 0 ];
const directions = [
[ 1, 0 ],
[ 0, 1 ],
[ -1, 0 ],
[ 0, -1 ],
];
let direction = 0;
const result = Array.from({ length: height }, n => Array(width).fill(null));
for (const n of data) {
result[position[1]][position[0]] = n;
if (null !== (result[position[1] + directions[direction][1]] || {})[position[0] + directions[direction][0]]) {
direction = (direction + 1) % directions.length;
}
position[0] += directions[direction][0];
position[1] += directions[direction][1];
}
return result.map(n => n.join(' ')).join('\n');
}
Примеры использования:
console.log(makeTable([ 'раз', 'два', 'три' ])); /*
р а з
р и д
т а в
*/
console.log(makeTable([ 'один', 'два', 'три', 'четыре' ])); /*
о д и н
е т ы д
ч е р в
и р т а
*/
console.log(makeTable([ 'hello', ',', ' ', 'world', '!!' ])); /*
h e
! l
! l
d o
l ,
r
o w
*/