Skip to content

Commit 58effa8

Browse files
sagarishereHarryVasanth
authored andcommitted
Improved checking for import, moved removeComments
Improved checking of imports and moved removeComments to separate function, clearly explaining that it's limited to javascript type of comments.
1 parent d69f6cb commit 58effa8

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

js/tests/test.mjs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -149,17 +149,27 @@ ${tests.trim()};`.trim()
149149
}
150150

151151
const loadAndSanitizeSolution = async () => {
152-
const path = `${solutionPath}/${name}.js`
153-
const rawCode = await read(path, "student solution")
154-
155-
// this is a very crude and basic removal of comments
156-
// since checking code is only use to prevent cheating
157-
// it's not that important if it doesn't work 100% of the time.
158-
const code = rawCode.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim()
159-
if (code.includes("import")) fatal("import keyword not allowed")
160-
return { code, rawCode, path }
152+
try {
153+
const path = `${solutionPath}/${name}.js`
154+
const rawCode = await read(path, "student solution")
155+
const sanitizedCode = removeComments(rawCode)
156+
157+
if (sanitizedCode.includes("import ")) { // space is important as it prevents "imported" or "importance" or other words containing "import"
158+
throw new Error("The use of the 'import' keyword is not allowed.")
159+
}
160+
return { code: sanitizedCode, rawCode, path }
161+
} catch (error) {
162+
console.error(error)
163+
}
161164
}
162165

166+
const removeComments = (code) => {
167+
// removes JS single line and multi-line comments only. Not for bash files etc.
168+
// for use with multiple file-types, I suggest writing a removeComments function with language-type as input and then handling accordingly
169+
return code.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim()
170+
}
171+
172+
163173
const runTests = async ({ url, path, code }) => {
164174
const { setup, tests } = await import(url).catch(err =>
165175
fatal(`Unable to execute ${name}, error:\n${stackFmt(err, url)}`),

0 commit comments

Comments
 (0)