1+ import fetch from "node-fetch" ;
2+ import fs from "fs" ;
3+
4+ const toc = async ( ) => {
5+ // Fetch from the GitHubAPI
6+ const data = await fetch (
7+ "https://api.github.com/repos/yashksaini-coder/September-Leetcode-Daily-2024/contents?ref=main"
8+ )
9+ . then ( ( response ) => response . json ( ) )
10+ . then ( ( data ) => data ) ;
11+
12+ var arr = Object . values ( data ) ;
13+
14+ // Filter out the folders
15+ const folders = arr . filter (
16+ ( item ) => item . type === "dir" && item . name [ 0 ] !== "."
17+ ) ;
18+
19+ // Make a table of contents
20+ var toc = [ ] ;
21+ folders . forEach ( ( item ) => {
22+ var num = parseInt ( item . name . split ( "-" ) [ 0 ] ) ;
23+ toc [ num ] = item . name ;
24+ } ) ;
25+
26+ // Sort toc by key
27+ var sorted = Object . keys ( toc )
28+ . sort ( )
29+ . reduce ( ( obj , key ) => {
30+ obj [ key ] = toc [ key ] ;
31+ return obj ;
32+ } , { } ) ;
33+
34+ // Generate the table of solutions
35+ let solutionsTable = `
36+ <!-- SOLUTIONS TABLE BEGIN -->
37+ | Leetcode Problem | Problem Statement | Solution |
38+ |---:|:-----|:----:|
39+ ` ;
40+ for ( var key in sorted ) {
41+ var str = sorted [ key ] . split ( "-" ) ;
42+ var name = str . slice ( 1 ) . join ( " " ) ;
43+ var num = key ;
44+ solutionsTable += `| [${ num } ](https://leetcode.com/problems/${ str . slice ( 1 ) . join ( "-" ) } /) | ${ name } | [Solution](./${ str . join ( "-" ) } /${ str . join ( "-" ) } .java) |\n` ;
45+ }
46+ solutionsTable += "<!-- SOLUTIONS TABLE END -->" ;
47+
48+ // Read the existing README content
49+ let readmeContent = fs . readFileSync ( "README.md" , "utf8" ) ;
50+
51+ // Checking whether the solutions table already exists
52+ if ( readmeContent . includes ( "<!-- SOLUTIONS TABLE BEGIN -->" ) ) {
53+ // Replacing the existing table
54+ readmeContent = readmeContent . replace (
55+ / < ! - - S O L U T I O N S T A B L E B E G I N - - > [ \s \S ] * < ! - - S O L U T I O N S T A B L E E N D - - > / ,
56+ solutionsTable
57+ ) ;
58+ } else {
59+ // Find the "## Solutions" heading and insert the table after it. It is necessary the heading matches exactly.
60+ const solutionsHeading = "## Solutions" ;
61+ const headingIndex = readmeContent . indexOf ( solutionsHeading ) ;
62+ if ( headingIndex !== - 1 ) {
63+ const insertIndex = headingIndex + solutionsHeading . length ;
64+ readmeContent = readmeContent . slice ( 0 , insertIndex ) + "\n\n" + solutionsTable + readmeContent . slice ( insertIndex ) ;
65+ } else {
66+ console . error ( "Could not find '## Solutions' heading in README.md" ) ;
67+ return ;
68+ }
69+ }
70+
71+ // Write the updated content back to README.md
72+ fs . writeFileSync ( "README.md" , readmeContent ) ;
73+ console . log ( "README.md has been updated with the solutions table!" ) ;
74+ } ;
75+
76+ toc ( ) ;
0 commit comments