Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
## Peetcode
It's an online algorithmic problem solving platform. Built as a joke during the full stack assignments by Harkirat Singh.
No intention of building this into a business.
Added code run functionality for python and c++, using nodejs child_process module. It creates a child process that I used to execute the code. I created a temporary file to store the code, then compile and execute it. Then it checks if the output is as desired. </br>
You need to print the answer to stdout, not just return it. </br>
For example, for problem 205. Add Two Numbers, if you print 300, it will display AC, WA otherwise. <br/>

If you would like to win an Airpods though, feel free to go through the third part and build the bounty described in the video
```
npm install
npm install uuid@latest
pm2 start index.js
```

Added a select element to let users select their language (currently only python and c++)

https://github.com/hridyeshK/peetcode/assets/101424471/2ea6a63f-0112-4192-ae5f-5ee8f788f2cf

Demo: https://peetcode.com
126 changes: 69 additions & 57 deletions client/src/Components/ProblemsPage/ProblemsPage.jsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,98 @@
import React, {useEffect, useState} from 'react'
import { useParams } from 'react-router-dom'

import "./ProblemsPage.css"
import {backendUrl} from "../../constants.js";
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import './ProblemsPage.css';
import { backendUrl } from '../../constants.js';

const ProblemsPage = () => {
const [CodeSeg, setCodeSeg] = useState("") ;
const { pid } = useParams() ;
const cleanId = pid.substring(1) ;
const [CodeSeg, setCodeSeg] = useState('');
const { pid } = useParams();
const cleanId = pid.substring(1);
const [problem, setProblem] = useState(null);
const [submission, setSubmission] = useState("");
const [submission, setSubmission] = useState('');
const [language, setLanguage] = useState('python');

const init = async () => {
const response = await fetch(`${backendUrl}/problem/` + cleanId, {
method: "GET",
});
const init = async () => {
const response = await fetch(`${backendUrl}/problem/` + cleanId, {
method: 'GET',
});

const json = await response.json();
setProblem(json.problem);
}
const json = await response.json();
setProblem(json.problem);
};

useEffect(() => {
init();
}, [])
// console.log(cleanId) ;

}, []);

const handleKey = (event) => {
if (event.key == "Tab"){
event.preventDefault() ;
const { selectionStart , selectionEnd , value } = event.target ;
const val = value.substring(0,selectionStart) + "\t" + value.substring(selectionStart) ;
if (event.key === 'Tab') {
event.preventDefault();
const { selectionStart, selectionEnd, value } = event.target;
const val = value.substring(0, selectionStart) + '\t' + value.substring(selectionStart);
event.target.value = val;
event.target.selectionStart = event.target.selectionEnd = selectionStart+1;
event.target.selectionStart = event.target.selectionEnd = selectionStart + 1;
}
setCodeSeg(event.value) ;
}
setCodeSeg(event.value);
};

return (
<div>

{
problem? (
<div id="problempage" className='flex-row'>
<div className="ques">
<h1>{problem.title}</h1>
<h5>Description</h5>
<p>{problem.description}</p>
<code>Input : {problem.exampleIn}</code>
<code>Output : {problem.exampleOut}</code>
</div>
<div className="code">
<h1>Code Here</h1>
<div className='code-form'>
<textarea onChange={(e) => setSubmission(e.target.value)} name="SolvedCode" onKeyDown={ (event) => handleKey(event) }></textarea>
<button type="submit" id="submit" onClick={async () => {
{problem ? (
<div id="problempage" className="flex-row">
<div className="ques">
<h1>{problem.title}</h1>
<h5>Description</h5>
<p>{problem.description}</p>
<code>Input: {problem.exampleIn}</code>
<code>Output: {problem.exampleOut}</code>
</div>
<div className="code">
<h1>Code Here</h1>
<div className="code-form">
<textarea
onChange={(e) => setSubmission(e.target.value)}
name="SolvedCode"
onKeyDown={(event) => handleKey(event)}
></textarea>
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
<option value="python">Python</option>
<option value="cpp">C++</option>
</select>
<button
type="submit"
id="submit"
onClick={async () => {
const response = await fetch(`${backendUrl}/submission`, {
method: "POST",
method: 'POST',
headers: {
"authorization": localStorage.getItem("token")
authorization: localStorage.getItem('token'),
'Content-Type': 'application/json',
},
body: JSON.stringify({
problemId: cleanId,
submission: submission
})
language: language,
submission: submission,
}),
});

const json = await response.json();
console.log(json);

}}>SubmitCode</button>
</div>
}}
>
Submit Code
</button>
</div>
</div>
) :
(<div>The searched Question Doesn't exist</div>)
}

</div>
) : (
<div>The searched Question Doesn't exist</div>
)}
</div>

)
}
);
};

export default ProblemsPage
export default ProblemsPage;
2 changes: 1 addition & 1 deletion client/src/constants.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const backendUrl = "https://api.peetcode.com";
export const backendUrl = "http://localhost:3000";
10 changes: 10 additions & 0 deletions server/code.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Your First C++ Program

#include <iostream>

int main() {
int a = 200; int b = 100;
std::cout << a+b;
return 0;
}

Binary file added server/code.out
Binary file not shown.
70 changes: 49 additions & 21 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const express = require("express");
const { execFile } = require("child_process");
const fs = require("fs");
const app = express();
const port = 3000;
var jwt = require("jsonwebtoken");
Expand Down Expand Up @@ -143,31 +145,57 @@ app.get("/submissions/:problemId", auth, (req, res) => {
});

app.post("/submission", auth, (req, res) => {
const isCorrect = Math.random() < 0.5;
const problemId = req.body.problemId;
const submission = req.body.submission;

if (isCorrect) {
SUBMISSIONS.push({
submission,
problemId,
userId: req.userId,
status: "AC",
});
return res.json({
status: "AC",
});
const language = req.body.language;

let command, args;

if (language === "python") {
command = "python";
args = ["-c", submission];
} else if (language === "cpp") {
const codeFilePath = `./code.${language}`;
fs.writeFileSync(codeFilePath, submission);
command = "g++";
args = [codeFilePath, "-o", "./code.out"];
} else {
SUBMISSIONS.push({
submission,
problemId,
userId: req.userId,
status: "WA",
});
return res.json({
status: "WA",
});
return res.status(400).json({ error: "Unsupported language" });
}

execFile(command, args, (error, stdout, stderr) => {
if (error) {
console.error(error);
return res.status(500).json({ status: "Runtime error" });
}

if (language === "cpp") {
execFile("./code.out", (error, stdout, stderr) => {
if (error) {
console.error(error);
return res.status(500).json({ status: "Runtime error" });
}

const output = stdout.trim().replace(/\r\n/g, "\n");
const problem = PROBLEMS.find((x) => x.problemId === problemId);

if (output === problem.exampleOut) {
return res.json({ status: "AC" });
} else {
return res.json({ status: "WA" });
}
});
} else {
const output = stdout.trim().replace(/\r\n/g, "\n");
const problem = PROBLEMS.find((x) => x.problemId === problemId);

if (output === problem.exampleOut) {
return res.json({ status: "AC" });
} else {
return res.json({ status: "WA" });
}
}
});
});

app.post("/signup", (req, res) => {
Expand Down
Loading