Skip to content

Commit 86f2a39

Browse files
committed
add solution to exercise 4.3
1 parent 8c38ca2 commit 86f2a39

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import fs from 'fs'
2+
import path from 'path'
3+
4+
const onError = err => console.error(err)
5+
6+
const checkKeywordInFile = (filePath, keyword, matchesCallback) => {
7+
fs.readFile(filePath, 'utf-8', (fileReadErr, fileContent) => {
8+
if (fileReadErr) {
9+
return matchesCallback(fileReadErr)
10+
}
11+
if (!fileContent) {
12+
return matchesCallback(null, false)
13+
}
14+
/* const resp = fileContent.split('\n').filter(line => line.includes(keyword))
15+
if (!resp.length) {
16+
return matchesCallback(null, false)
17+
}
18+
matchesCallback(null, true) */
19+
20+
return matchesCallback(null, fileContent.includes(keyword))
21+
})
22+
}
23+
24+
const findFileMatches = (dir, keyword, matches, cb) => {
25+
fs.readdir(dir, { withFileTypes: true }, (readDirErr, files) => {
26+
if (readDirErr) {
27+
return cb(readDirErr)
28+
}
29+
30+
let completed = 0
31+
32+
const { dirFiles, subDirs } = files.reduce((acc, curr) => {
33+
acc[curr.isFile() ? 'dirFiles' : 'subDirs'].push(curr)
34+
return acc
35+
}, { dirFiles: [], subDirs: [] })
36+
37+
function iterate(index) {
38+
if (index === subDirs.length) {
39+
return cb(null, matches)
40+
}
41+
42+
const newDirPath = path.join(dir, subDirs[index].name)
43+
findFileMatches(newDirPath, keyword, matches, () => {
44+
iterate(index + 1)
45+
})
46+
}
47+
48+
function doneCheck() {
49+
// when finished searching for a match in the current files continue with the next directory
50+
if (++completed === dirFiles.length) {
51+
return iterate(0)
52+
}
53+
}
54+
55+
dirFiles.forEach(file => {
56+
const filePath = path.join(dir, file.name)
57+
58+
checkKeywordInFile(filePath, keyword, (_, matching) => {
59+
if (matching) {
60+
matches.push(filePath)
61+
}
62+
doneCheck()
63+
})
64+
})
65+
})
66+
}
67+
68+
const recursiveFind = (dirPath, keyword, finalCallback) => {
69+
findFileMatches(dirPath, keyword, [], (err, matches) => {
70+
if (err) {
71+
return onError(err)
72+
}
73+
finalCallback(matches)
74+
})
75+
}
76+
77+
recursiveFind('./filesToConcat', 'batman', console.log)

0 commit comments

Comments
 (0)