HireCamp Coding Sandbox

HireCamp Coding Sandbox

Practice, Test & Learn Coding Instantly

index.html
Output / Terminal
Press Run Code to see output here or type a command below ↓
$
🔒 Code runs in a temporary sandbox environment — no data is saved, no server access, no file system access.
Light Mode
Font:
Sandbox Active
Powered by HireCamp Academy – Practice Coding Without Setup
`, css: `/* HireCamp CSS Sandbox */ body { margin: 0; font-family: 'Segoe UI', sans-serif; background: linear-gradient(135deg, #a21d20, #1e3a5f); min-height: 100vh; display: flex; align-items: center; justify-content: center; } .card { background: white; border-radius: 16px; padding: 40px; max-width: 400px; text-align: center; box-shadow: 0 20px 60px rgba(0,0,0,.3); } .card h1 { color: #a21d20; margin-bottom: 10px; } .card p { color: #666; line-height: 1.6; } .btn { display: inline-block; margin-top: 16px; padding: 10px 28px; background: #a21d20; color: white; border-radius: 8px; font-weight: bold; cursor: pointer; border: none; transition: transform .2s, box-shadow .2s; } .btn:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(162,29,32,.4); }`, javascript: `// HireCamp JavaScript Sandbox // Open your browser console (F12) to see logsconsole.log("🚀 HireCamp Sandbox Ready!");// Example: Fibonacci sequence function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }console.log("Fibonacci Sequence (first 10):"); for (let i = 0; i < 10; i++) { console.log(\` F(\${i}) = \${fibonacci(i)}\`); }// Example: DOM manipulation document.body.style.cssText = \` font-family: Arial, sans-serif; background: #0f172a; color: #e2e8f0; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; \`; document.body.innerHTML = \`

🎉 JS Sandbox

Open console to see Fibonacci logs

\`;`, python: `# HireCamp Python Sandbox (Simulated) # Note: Python runs in simulation modeprint("🐍 HireCamp Python Sandbox") print("=" * 35)# Fibonacci def fibonacci(n): a, b = 0, 1 result = [] for _ in range(n): result.append(a) a, b = b, a + b return resultprint("Fibonacci sequence (10 terms):") print(fibonacci(10))# List comprehension squares = [x**2 for x in range(1, 11)] print("\\nSquares of 1-10:") print(squares)# String manipulation name = "HireCamp Academy" print(f"\\nWelcome to {name}!") print(f"Length: {len(name)} characters") print(f"Uppercase: {name.upper()}")`, c: `// HireCamp C Sandbox (Simulated) #include int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); }int main() { printf("🔧 HireCamp C Sandbox\\n"); printf("========================\\n"); // Fibonacci printf("Fibonacci sequence:\\n"); for (int i = 0; i < 10; i++) { printf(" F(%d) = %d\\n", i, fibonacci(i)); } // Array example int arr[] = {5, 2, 8, 1, 9, 3}; int n = sizeof(arr)/sizeof(arr[0]); printf("\\nArray: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\\n"); return 0; }`, cpp: `// HireCamp C++ Sandbox (Simulated) #include #include #include using namespace std;class Student { public: string name; int score; Student(string n, int s) : name(n), score(s) {} };int main() { cout << "🔷 HireCamp C++ Sandbox" << endl; cout << string(30, '=') << endl; vector students = { {"Alice", 95}, {"Bob", 82}, {"Carol", 91}, {"Dave", 78} }; sort(students.begin(), students.end(), [](const Student& a, const Student& b){ return a.score > b.score; }); cout << "\\nStudent Rankings:" << endl; for (int i = 0; i < students.size(); i++) { cout << " " << i+1 << ". " << students[i].name << " - " << students[i].score << "/100" << endl; } return 0; }`, java: `// HireCamp Java Sandbox (Simulated) import java.util.*; import java.util.stream.*;public class Main { static int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } public static void main(String[] args) { System.out.println("☕ HireCamp Java Sandbox"); System.out.println("=".repeat(30)); // Fibonacci System.out.println("\\nFibonacci sequence (10 terms):"); IntStream.range(0, 10) .forEach(i -> System.out.printf(" F(%d) = %d%n", i, fibonacci(i))); // Collections List languages = Arrays.asList( "Java", "Python", "JavaScript", "C++", "Go"); System.out.println("\\nPopular languages (sorted):"); languages.stream().sorted() .forEach(lang -> System.out.println(" • " + lang)); } }` };/* ── SIMULATED OUTPUT ── */ const SIMULATED = { python: [ { t: 'info', v: '🐍 HireCamp Python Sandbox' }, { t: 'info', v: '===================================' }, { t: '', v: 'Fibonacci sequence (10 terms):' }, { t: '', v: '[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]' }, { t: '', v: '' }, { t: '', v: 'Squares of 1-10:' }, { t: '', v: '[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]' }, { t: '', v: '' }, { t: '', v: 'Welcome to HireCamp Academy!' }, { t: '', v: 'Length: 16 characters' }, { t: '', v: 'Uppercase: HIRECAMP ACADEMY' }, { t: 'prompt', v: '' }, { t: 'prompt', v: '>>> Process finished with exit code 0' }, ], c: [ { t: 'info', v: '🔧 HireCamp C Sandbox' }, { t: 'info', v: '========================' }, { t: '', v: 'Fibonacci sequence:' }, { t: '', v: ' F(0) = 0\n F(1) = 1\n F(2) = 1\n F(3) = 2\n F(4) = 3\n F(5) = 5\n F(6) = 8\n F(7) = 13\n F(8) = 21\n F(9) = 34' }, { t: '', v: '' }, { t: '', v: 'Array: 5 2 8 1 9 3' }, { t: 'prompt', v: '' }, { t: 'prompt', v: '[Process exited with code 0]' }, ], cpp: [ { t: 'info', v: '🔷 HireCamp C++ Sandbox' }, { t: 'info', v: '==============================' }, { t: '', v: '' }, { t: '', v: 'Student Rankings:' }, { t: '', v: ' 1. Alice - 95/100\n 2. Carol - 91/100\n 3. Bob - 82/100\n 4. Dave - 78/100' }, { t: 'prompt', v: '' }, { t: 'prompt', v: '[Process exited with code 0]' }, ], java: [ { t: 'info', v: '☕ HireCamp Java Sandbox' }, { t: 'info', v: '==============================' }, { t: '', v: '' }, { t: '', v: 'Fibonacci sequence (10 terms):' }, { t: '', v: ' F(0) = 0\n F(1) = 1\n F(2) = 1\n F(3) = 2\n F(4) = 3\n F(5) = 5\n F(6) = 8\n F(7) = 13\n F(8) = 21\n F(9) = 34' }, { t: '', v: '' }, { t: '', v: 'Popular languages (sorted):' }, { t: '', v: ' • C++\n • Go\n • Java\n • JavaScript\n • Python' }, { t: 'prompt', v: '' }, { t: 'prompt', v: '[BUILD SUCCESSFUL in 0.8s]' }, ] };/* ── LANG CONFIG ── */ const LANG_CFG = { html: { mode: 'htmlmixed', file: 'index.html', web: true }, css: { mode: 'css', file: 'style.css', web: true }, javascript: { mode: 'javascript', file: 'script.js', web: true }, python: { mode: 'python', file: 'main.py', web: false }, c: { mode: 'text/x-csrc', file: 'main.c', web: false }, cpp: { mode: 'text/x-c++src', file: 'main.cpp', web: false }, java: { mode: 'text/x-java', file: 'Main.java', web: false }, };/* ── INIT CODEMIRROR ── */ let currentLang = 'html'; let autoRun = false; let autoRunTimer = null;// Per-language code storage — preserves what user typed when switching tabs const perLangCode = {}; Object.keys(LANG_CFG).forEach(k => { perLangCode[k] = DEFAULTS[k]; });const cm = CodeMirror.fromTextArea(document.getElementById('codeEditor'), { mode: 'htmlmixed', theme: 'dracula', lineNumbers: true, autoCloseBrackets: true, matchBrackets: true, styleActiveLine: true, indentUnit: 2, tabSize: 2, indentWithTabs: false, lineWrapping: false, extraKeys: { 'Ctrl-Enter': runCode, 'Cmd-Enter': runCode, } }); cm.setValue(DEFAULTS.html);cm.on('change', () => { if (autoRun) { clearTimeout(autoRunTimer); autoRunTimer = setTimeout(runCode, 1200); } });/* ── LANGUAGE SWITCH ── */ document.getElementById('langTabs').addEventListener('click', e => { const tab = e.target.closest('.lang-tab'); if (!tab) return; const lang = tab.dataset.lang; if (!lang) return; switchLang(lang); });function switchLang(lang) { const cfg = LANG_CFG[lang]; if (!cfg) return; // Save current code before switching if (currentLang) perLangCode[currentLang] = cm.getValue(); document.querySelectorAll('.lang-tab').forEach(t => t.classList.toggle('active', t.dataset.lang === lang)); cm.setOption('mode', cfg.mode); // Restore this language's saved code (or default if first time) cm.setValue(perLangCode[lang] || DEFAULTS[lang]); document.getElementById('fileLabel').textContent = cfg.file; currentLang = lang; clearOutput(); if (autoRun) runCode(); }/* ── RUN CODE ── */ const btnRun = document.getElementById('btnRun'); btnRun.addEventListener('click', runCode);function runCode() { const cfg = LANG_CFG[currentLang]; const code = cm.getValue(); // Save current code perLangCode[currentLang] = code; btnRun.classList.add('running'); btnRun.disabled = true; hideEmpty();if (currentLang === 'python') { // Skulpt is async — handle separately setTimeout(() => runPython(code), 300); return; } const delay = cfg.web ? 200 : 900; setTimeout(() => { if (cfg.web) { runWeb(currentLang, code); } else { runSimulated(currentLang, code); } btnRun.classList.remove('running'); btnRun.disabled = false; }, delay); }function runWeb(lang, code) { const iframe = document.getElementById('outputIframe'); const console_ = document.getElementById('outputConsole'); iframe.style.display = 'block'; console_.style.display = 'none';let html = ''; if (lang === 'html') { html = code; } else if (lang === 'css') { html = `

CSS Preview

Your styles are applied here.

`; } else if (lang === 'javascript') { // Capture console.log and show in output panel const consoleEl2 = document.getElementById('outputConsole'); consoleEl2.style.display = 'block'; consoleEl2.innerHTML = '
$ Running JavaScript...
'; html = ``; } iframe.srcdoc = html; document.getElementById('statusDot').style.background = '#22c55e'; }/* ── PYTHON via Skulpt ── */ function runPython(code) { const iframe = document.getElementById('outputIframe'); const consoleEl = document.getElementById('outputConsole'); iframe.style.display = 'none'; consoleEl.style.display = 'block'; consoleEl.innerHTML = '
$ python3 main.py
';function addOut(text, cls) { text.split('\n').forEach(line => { const el = document.createElement('div'); el.className = 'console-line' + (cls ? ' ' + cls : ''); el.textContent = line; consoleEl.appendChild(el); consoleEl.scrollTop = consoleEl.scrollHeight; }); }if (typeof Sk !== 'undefined') { Sk.configure({ output: txt => addOut(txt.replace(/\n$/, ''), ''), read: f => { if (Sk.builtinFiles && Sk.builtinFiles.files[f]) return Sk.builtinFiles.files[f]; throw '\'' + f + '\' not found'; }, __future__: Sk.python3 }); Sk.misceval.asyncToPromise(() => Sk.importMainWithBody('', false, code, true)) .then(() => { addOut('', ''); addOut('[Process finished with exit code 0]', 'prompt'); document.getElementById('statusDot').style.background = '#22c55e'; }) .catch(err => { addOut(String(err), 'error'); document.getElementById('statusDot').style.background = '#f87171'; }); } else { addOut('Python interpreter loading... Please try again in a moment.', 'info'); } document.getElementById('btnRun').classList.remove('running'); document.getElementById('btnRun').disabled = false; }/* ── SMART PARSER for C/C++/Java ── */ function parsePrintStatements(lang, code) { const results = []; const lines = code.split('\n');if (lang === 'c' || lang === 'cpp') { // Parse printf("...") and cout << "..." for (const line of lines) { let m; // printf("string") or printf("string\n") m = line.match(/printf\s*\(\s*"((?:[^"\\]|\\.)*)"/); if (m) { let s = m[1].replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\r/g, '').replace(/\\"/g, '"').replace(/\\'/g, '\''); // Remove format specifiers s = s.replace(/%[\-+0-9.*]*[diouxXeEfgGscp]/g, ''); results.push(s); continue; } // cout << "string" and cout << endl if (lang === 'cpp') { const coutLine = line.match(/cout\s*<<(.+)/); if (coutLine) { const parts = coutLine[1].split('<<'); let out = ''; for (const p of parts) { const str = p.match(/"((?:[^"\\]|\\.)*)"|'(.)'/); if (p.trim() === 'endl' || p.trim() === '"\\n"') { out += '\n'; } else if (str) { out += str[1] || str[2] || ''; } else { out += ''; } } results.push(out.replace(/\\n/g, '\n').replace(/\\t/g, '\t')); continue; } } } } else if (lang === 'java') { for (const line of lines) { // System.out.println("...") and System.out.print("...") let m = line.match(/System\.out\.print(?:ln)?\s*\(\s*"((?:[^"\\]|\\.)*)"|System\.out\.print(?:ln)?\s*\(([^)]+)\)/); if (m) { let s = (m[1] || m[2] || '').replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\"/g, '"'); if (line.includes('println')) s += '\n'; results.push(s); } } } return results; }function runSimulated(lang, code) { const iframe = document.getElementById('outputIframe'); const consoleEl = document.getElementById('outputConsole'); iframe.style.display = 'none'; consoleEl.style.display = 'block'; consoleEl.innerHTML = '';function addLine(text, cls) { text.split('\n').forEach(t => { const el = document.createElement('div'); el.className = 'console-line' + (cls ? ' ' + cls : ''); el.textContent = t; consoleEl.appendChild(el); consoleEl.scrollTop = consoleEl.scrollHeight; }); }// Header const cmds = { c: '$ gcc main.c -o main && ./main', cpp: '$ g++ -std=c++17 main.cpp -o main && ./main', java: '$ javac Main.java && java Main' }; addLine(cmds[lang] || '$ running...', 'info');// Try to extract actual print statements const parsed = parsePrintStatements(lang, code); let i = 0;function next() { if (i >= parsed.length) { addLine('', ''); addLine('[Process exited with code 0]', 'prompt'); document.getElementById('statusDot').style.background = '#22c55e'; return; } addLine(parsed[i++], ''); setTimeout(next, 60); }if (parsed.length > 0) { setTimeout(next, 60); } else { // Fallback: show a note about simulation addLine('(No print statements detected — showing simulation)', 'info'); addLine('', ''); const SIMULATED = { c: '🔧 C program ran.\n[Process exited with code 0]', cpp: '🔷 C++ program ran.\n[Process exited with code 0]', java: '☕ Java program ran.\n[BUILD SUCCESSFUL]', }; addLine(SIMULATED[lang] || 'Done.', 'prompt'); document.getElementById('statusDot').style.background = '#22c55e'; } }function hideEmpty() { document.getElementById('outputEmpty').style.display = 'none'; }function clearOutput() { const iframe = document.getElementById('outputIframe'); const consoleEl = document.getElementById('outputConsole'); iframe.style.display = 'none'; iframe.srcdoc = ''; consoleEl.style.display = 'none'; consoleEl.innerHTML = ''; document.getElementById('outputEmpty').style.display = ''; document.getElementById('statusDot').style.background = '#22c55e'; }document.getElementById('btnClearOutput').addEventListener('click', clearOutput);/* ── RESET ── */ document.getElementById('btnReset').addEventListener('click', () => { if (!confirm('Reset code to default?')) return; perLangCode[currentLang] = DEFAULTS[currentLang]; cm.setValue(DEFAULTS[currentLang]); clearOutput(); });/* ── COPY ── */ document.getElementById('btnCopy').addEventListener('click', () => { navigator.clipboard.writeText(cm.getValue()).then(() => { const b = document.getElementById('btnCopy'); b.textContent = '✅'; setTimeout(() => b.textContent = '📋', 1500); }); });/* ── DOWNLOAD ── */ document.getElementById('btnDownload').addEventListener('click', () => { const cfg = LANG_CFG[currentLang]; const blob = new Blob([cm.getValue()], { type: 'text/plain' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = cfg.file; a.click(); });/* ── AUTO RUN TOGGLE ── */ const btnAutoRun = document.getElementById('btnAutoRun'); btnAutoRun.addEventListener('click', () => { autoRun = !autoRun; btnAutoRun.style.background = autoRun ? '#a21d20' : ''; btnAutoRun.style.color = autoRun ? '#fff' : ''; btnAutoRun.style.border = autoRun ? 'none' : ''; btnAutoRun.title = autoRun ? 'Auto-run ON (click to off)' : 'Toggle auto-run'; });/* ── JS CONSOLE CAPTURE (postMessage from iframe) ── */ window.addEventListener('message', e => { if (!e.data || e.data.type !== 'console') return; if (currentLang !== 'javascript') return; const consoleEl = document.getElementById('outputConsole'); const el = document.createElement('div'); const cls = e.data.level === 'error' ? 'error' : e.data.level === 'warn' ? 'prompt' : ''; el.className = 'console-line' + (cls ? ' ' + cls : ''); el.textContent = e.data.text; consoleEl.appendChild(el); consoleEl.scrollTop = consoleEl.scrollHeight; });/* ── SHARE ── */ document.getElementById('btnShareCode').addEventListener('click', () => { try { const encoded = btoa(unescape(encodeURIComponent(cm.getValue()))); const url = location.href.split('#')[0] + '#code=' + encoded + '&lang=' + currentLang; navigator.clipboard.writeText(url).then(() => { alert('📎 Share link copied to clipboard!'); }); } catch (e) { alert('Could not generate share link for this code size.'); } });/* ── LOAD FROM HASH ── */ (function loadFromHash() { const hash = location.hash.slice(1); if (!hash) return; const params = Object.fromEntries(new URLSearchParams(hash)); if (params.lang && LANG_CFG[params.lang]) switchLang(params.lang); if (params.code) { try { cm.setValue(decodeURIComponent(escape(atob(params.code)))); } catch (e) { } } })();/* ── FULLSCREEN ── */ document.getElementById('btnFullscreen').addEventListener('click', () => { document.body.classList.toggle('fullscreen'); document.getElementById('btnFullscreen').textContent = document.body.classList.contains('fullscreen') ? '⊡ Exit' : '⛶ Full'; }); document.addEventListener('keydown', e => { if (e.key === 'Escape') document.body.classList.remove('fullscreen'); });/* ── THEME TOGGLE ── */ document.getElementById('themeToggle').addEventListener('change', function () { document.body.classList.toggle('dark', !this.checked); document.body.classList.toggle('light', this.checked); cm.setOption('theme', this.checked ? 'eclipse' : 'dracula'); });/* ── FONT SIZE ── */ document.getElementById('fontSizeSelect').addEventListener('change', function () { document.querySelector('.CodeMirror').style.fontSize = this.value + 'px'; cm.refresh(); });/* ── SPLITTER / RESIZE ── */ const splitter = document.getElementById('splitter'); const editorPanel = document.getElementById('editorPanel'); const outputPanel = document.getElementById('outputPanel'); const workspace = document.getElementById('workspace'); let isResizing = false;splitter.addEventListener('mousedown', e => { isResizing = true; splitter.classList.add('dragging'); document.body.style.userSelect = 'none'; document.body.style.cursor = 'col-resize'; e.preventDefault(); });document.addEventListener('mousemove', e => { if (!isResizing) return; const rect = workspace.getBoundingClientRect(); const total = rect.width; const leftW = ((e.clientX - rect.left) / total * 100).toFixed(1); if (leftW < 20 || leftW > 80) return; editorPanel.style.width = leftW + '%'; outputPanel.style.flex = 'none'; outputPanel.style.width = (100 - leftW - 0.5) + '%'; cm.refresh(); });document.addEventListener('mouseup', () => { if (!isResizing) return; isResizing = false; splitter.classList.remove('dragging'); document.body.style.userSelect = ''; document.body.style.cursor = ''; cm.refresh(); });})();