Skip to content

Commit 9ceacf0

Browse files
committedDec 19, 2024·
Solution challenge 15 v2
1 parent 3968810 commit 9ceacf0

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed
 

‎challenges-2024/challenge-15/drawTable.js

+25-6
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
11
export function drawTable(data) {
2-
const line = `+${'-'.repeat(10)}+${'-'.repeat(10)}+`
2+
function toUpperCase(input) {
3+
const firstLetter = input.charAt(0).toUpperCase()
4+
return firstLetter + input.slice(1)
5+
}
6+
37
const keys = Object.keys(data[0])
4-
const headerKeys = keys.map(key => `| ${key.charAt(0).toUpperCase()}${key.padEnd(9).slice(1)}`).join('') + '|'
5-
const header = `${line}\n${headerKeys}\n${line}`
6-
const body = data
8+
const columnLengths = keys.map(key => key.length)
9+
10+
const rows = data.map(row => {
11+
return keys.map((key, index) => {
12+
const value = row[key].toString()
13+
columnLengths[index] = Math.max(columnLengths[index], value.length)
14+
return value
15+
})
16+
})
17+
18+
const line = `+-${columnLengths.map(length => '-'.repeat(length)).join('-+-')}-+`
19+
const header = `| ${keys
20+
.map((key, index) => {
21+
return toUpperCase(key).padEnd(columnLengths[index])
22+
})
23+
.join(' | ')} |`
24+
25+
const body = rows
726
.map(row => {
8-
return keys.map(key => `| ${row[key].padEnd(9)}`).join('') + '|'
27+
return `| ${row.map((value, index) => value.padEnd(columnLengths[index])).join(' | ')} |`
928
})
1029
.join('\n')
1130

12-
return `${header}\n${body}\n${line}`
31+
return `${line}\n${header}\n${line}\n${body}\n${line}`
1332
}
1433

1534
const result = drawTable([

0 commit comments

Comments
 (0)
Please sign in to comment.