File tree 1 file changed +25
-6
lines changed
challenges-2024/challenge-15
1 file changed +25
-6
lines changed Original file line number Diff line number Diff line change 1
1
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
+
3
7
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
7
26
. map ( row => {
8
- return keys . map ( key => `| ${ row [ key ] . padEnd ( 9 ) } ` ) . join ( '' ) + '|'
27
+ return `| ${ row . map ( ( value , index ) => value . padEnd ( columnLengths [ index ] ) ) . join ( ' | ' ) } |`
9
28
} )
10
29
. join ( '\n' )
11
30
12
- return `${ header } \n${ body } \n${ line } `
31
+ return `${ line } \n ${ header } \n ${ line } \n${ body } \n${ line } `
13
32
}
14
33
15
34
const result = drawTable ( [
You can’t perform that action at this time.
0 commit comments