about summary refs log blame commit diff stats
path: root/html/playground/little-regex.html
blob: c09139f17c842d4d9f15c8d545c64ebfaab210d8 (plain) (tree)
fd783bb ^

















































































































































































































































































































































































































































































































































































<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Choice-based Game</title>
  <link rel="stylesheet" href="./styles.css">
</head>
<body>
  <div id="app"></div>
  <script type="module" src="./js/game.js"></script>
</body>
</html>
235' href='#n235'>235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728























































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                         
<html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Playground</title>
    <meta name="description" content="A JavaScript jungle-gym for doing experiments and sharing scrappy fiddles.">
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #ddd;
            padding: 10px;
            height: 100vh;
            margin: 0;
        }

        textarea {
            width: 100%;
            height: 64%;
            font-family: monospace;
            background-color: #FFFEEC;
            border: 2px solid #000;
            scrollbar-width: none;            
            font-size: 1rem;
            margin-bottom: 10px;
            padding: 10px;
            box-sizing: border-box;
            resize: none;
            border-bottom: 12px solid teal;
            -webkit-user-modify: read-write-plaintext-only;
        }

        textarea::-webkit-scrollbar {
            display: none;
        }

        textarea::selection {
            background-color: #EFECA7;
        }

        textarea:focus {
            outline: none;
        }

        #console {
            width: 100%;
            height: 22%;
            background-color: #000;
            color: #0fc;
            font-family: monospace;
            font-size: 1rem;
            overflow-y: auto;
            padding: 10px;
            box-sizing: border-box;
            white-space: pre-wrap;
        }

        .button-container {
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-bottom: 10px;
        }

        button {
            padding: 10px 20px;
            font-size: 1rem;
            margin-left: 10px;
            cursor: pointer;
            border: none;
            transition: background-color 0.3s ease;
        }

        button:hover, button:focus {
            outline: none; 
        }

        button.run {
            background-color: teal;
            color: #FFFFFF;
        }
    </style>
</head>
<body>

    <div class="playground" id="playground">    
        <div class="seesaw" id="seesaw"></div>
        <div class="slide" id="slide"></div>
    </div>

    <div class="button-container">
        <button onclick="clearEverything()">Clear</button>
        <button onclick="downloadCodeAndEditor()">Download</button>
        <button onclick="shareCode()">Share</button>
        <button onclick="evaluateCode()" class="run">Run Code</button>
    </div>
    <textarea id="codeInput">// Inspired by <https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html>
const matchHere = (pattern, text) => {
    if (pattern.length === 0) return true;
    
    // If pattern ends with $, match end of string
    if (pattern[0] === '
    <div id="console"></div>

    <script>
        function evaluateCode() {
            const code = document.getElementById('codeInput').value;
            const consoleDiv = document.getElementById('console');
            consoleDiv.innerHTML = '';

            // Custom console.log function to output to the console div
            const originalConsoleLog = console.log;
            console.log = function(...args) {
                args.forEach(arg => {
                    const output = document.createElement('div');
                    output.textContent = typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg;
                    consoleDiv.appendChild(output);
                });
                originalConsoleLog.apply(console, args);
            };

            try {
                eval(code);
            } catch (error) {
                const errorOutput = document.createElement('div');
                errorOutput.textContent = error;
                errorOutput.style.color = 'red';
                consoleDiv.appendChild(errorOutput);
            }

            // Restore browser's console.log
            console.log = originalConsoleLog;
        }

        function downloadCodeAndEditor() {
            const codeInput = document.getElementById('codeInput').value;
            const htmlContent = document.documentElement.outerHTML.replace(
                /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
                `<textarea id="codeInput">${codeInput}</textarea>`
            );

            const blob = new Blob([htmlContent], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'code_editor.html';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function shareCode() {
            const code = document.getElementById('codeInput').value;
            const encodedCode = btoa(encodeURIComponent(code));
            window.location.hash = encodedCode;
            window.prompt("Copy the URL to share.\nBe warned! Very long URLs don't share wicked well, sometimes.", window.location.href);
        }

        function clearEverything() {
            if (!confirm('Are you sure you want to reset the playground?')) {
                return;
            } else {               
                window.location.hash = '';
                window.location.reload();
            }
        }

        function loadCodeFromHash() {
            const hash = window.location.hash.substring(1);
            if (hash) {
                try {
                    const decodedCode = decodeURIComponent(atob(hash));
                    document.getElementById('codeInput').value = decodedCode;
                } catch (error) {
                    console.error('Failed to decode the URL hash:', error);
                }
            }
        }

        function help() {
            const helpText = `
            Welcome to the JavaScript Playground! Here are some tips to get you started:

            1. Enter your JavaScript code in the textarea.
            2. Click the "Run Code" button to execute your code.
            3. The console output will be displayed below the textarea.
            4. Click the "Clear" button to reset the playground.
            5. Click the "Download" button to save your code and editor as an HTML file.
            6. Click the "Share" button to generate a URL to share your code with others.
            7. You can also press "Cmd + Enter" to run your code.
            8. There's an empty div above the buttons with the id "playground"
            9. You can mount stuff to it using the "mount" function, for more info run "mountHelp()"
            10. You can use the "clear()" function to clear the content's of the console.

            Go nuts! Share scrappy fiddles!
            `;
            console.log(helpText);
        }

        function clear() {
            document.getElementById('console').innerHTML = '';
        }

        function mountHelp() {
            console.log(`
            The mount function is used to mount stuff to the playground div.
            It takes a function as an argument, which in turn receives the playground div as an argument.
            Before mounting, it clears the playground div.
            Here's an example of how to use the mount function:

            mount(playground => {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hell is empty and all the devils are here.';
                playground.appendChild(h1);
            });

            This will add an h1 element to the playground div.
            `);
        }

        function mount(mountFunction) {
            const playground = document.getElementById('playground');
            if (!playground) {
                console.error("Couldn't find a div with the id 'playground'! You may need to reload the page.");
                return;
            }

            if (playground.innerHTML.trim() !== "") {
                playground.innerHTML = "";
            }
            mountFunction(playground);
        }


        document.getElementById('codeInput').addEventListener('keydown', function(event) {
            if (event.metaKey && event.key === 'Enter') {
                event.preventDefault();
                evaluateCode();
            }
        });

        window.onload = loadCodeFromHash;
    </script>


</body></html> && pattern.length === 1) return text.length === 0;

    // If next char is '*', match zero or more occurrences of prev char
    if (pattern[1] === '*') return matchStar(pattern[0], pattern.slice(2), text);

    // Match . or literal character
    if (text.length !== 0 && (pattern[0] === '.' || pattern[0] === text[0])) {
        return matchHere(pattern.slice(1), text.slice(1));
    }

    return false;
};

const matchStar = (prevChar, pattern, text) => {
    // Try matching zero occurrences first
    if (matchHere(pattern, text)) return true;

    // Then, match one or more occurrences of prevChar
    while (text.length > 0 && (text[0] === prevChar || prevChar === '.')) {
        text = text.slice(1);
        if (matchHere(pattern, text)) return true;
    }

    return false;
};

const match = (pattern, text) => {
    // Handle ^ anchor at the beginning
    if (pattern[0] === '^') {
        return matchHere(pattern.slice(1), text);
    }

    // Otherwise, check the entire string
    for (let i = 0; i <= text.length; i++) {
        if (matchHere(pattern, text.slice(i))) return true;
    }

    return false;
};

const assertEqual = (actual, expected, testName) => 
    console.log(actual === expected ? `Passed: ${testName}` : `Failed: ${testName}. Expected ${expected} but got ${actual}`);

assertEqual(match("ab*c", "ac"), true, "Star match 'ab*c' vs 'ac' (zero occurrences)");
assertEqual(match("ab*c", "abbbc"), true, "Star match 'ab*c' vs 'abbbc' (multiple occurrences)");
assertEqual(match("^ab.*c$", "abc"), true, "Complex match '^ab.*c
    <div id="console"></div>

    <script>
        function evaluateCode() {
            const code = document.getElementById('codeInput').value;
            const consoleDiv = document.getElementById('console');
            consoleDiv.innerHTML = '';

            // Custom console.log function to output to the console div
            const originalConsoleLog = console.log;
            console.log = function(...args) {
                args.forEach(arg => {
                    const output = document.createElement('div');
                    output.textContent = typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg;
                    consoleDiv.appendChild(output);
                });
                originalConsoleLog.apply(console, args);
            };

            try {
                eval(code);
            } catch (error) {
                const errorOutput = document.createElement('div');
                errorOutput.textContent = error;
                errorOutput.style.color = 'red';
                consoleDiv.appendChild(errorOutput);
            }

            // Restore browser's console.log
            console.log = originalConsoleLog;
        }

        function downloadCodeAndEditor() {
            const codeInput = document.getElementById('codeInput').value;
            const htmlContent = document.documentElement.outerHTML.replace(
                /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
                `<textarea id="codeInput">${codeInput}</textarea>`
            );

            const blob = new Blob([htmlContent], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'code_editor.html';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function shareCode() {
            const code = document.getElementById('codeInput').value;
            const encodedCode = btoa(encodeURIComponent(code));
            window.location.hash = encodedCode;
            window.prompt("Copy the URL to share.\nBe warned! Very long URLs don't share wicked well, sometimes.", window.location.href);
        }

        function clearEverything() {
            if (!confirm('Are you sure you want to reset the playground?')) {
                return;
            } else {               
                window.location.hash = '';
                window.location.reload();
            }
        }

        function loadCodeFromHash() {
            const hash = window.location.hash.substring(1);
            if (hash) {
                try {
                    const decodedCode = decodeURIComponent(atob(hash));
                    document.getElementById('codeInput').value = decodedCode;
                } catch (error) {
                    console.error('Failed to decode the URL hash:', error);
                }
            }
        }

        function help() {
            const helpText = `
            Welcome to the JavaScript Playground! Here are some tips to get you started:

            1. Enter your JavaScript code in the textarea.
            2. Click the "Run Code" button to execute your code.
            3. The console output will be displayed below the textarea.
            4. Click the "Clear" button to reset the playground.
            5. Click the "Download" button to save your code and editor as an HTML file.
            6. Click the "Share" button to generate a URL to share your code with others.
            7. You can also press "Cmd + Enter" to run your code.
            8. There's an empty div above the buttons with the id "playground"
            9. You can mount stuff to it using the "mount" function, for more info run "mountHelp()"
            10. You can use the "clear()" function to clear the content's of the console.

            Go nuts! Share scrappy fiddles!
            `;
            console.log(helpText);
        }

        function clear() {
            document.getElementById('console').innerHTML = '';
        }

        function mountHelp() {
            console.log(`
            The mount function is used to mount stuff to the playground div.
            It takes a function as an argument, which in turn receives the playground div as an argument.
            Before mounting, it clears the playground div.
            Here's an example of how to use the mount function:

            mount(playground => {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hell is empty and all the devils are here.';
                playground.appendChild(h1);
            });

            This will add an h1 element to the playground div.
            `);
        }

        function mount(mountFunction) {
            const playground = document.getElementById('playground');
            if (!playground) {
                console.error("Couldn't find a div with the id 'playground'! You may need to reload the page.");
                return;
            }

            if (playground.innerHTML.trim() !== "") {
                playground.innerHTML = "";
            }
            mountFunction(playground);
        }


        document.getElementById('codeInput').addEventListener('keydown', function(event) {
            if (event.metaKey && event.key === 'Enter') {
                event.preventDefault();
                evaluateCode();
            }
        });

        window.onload = loadCodeFromHash;
    </script>


</body></html> vs 'abc'");
assertEqual(match("^ab.*c$", "abcd"), false, "Complex mismatch '^ab.*c
    <div id="console"></div>

    <script>
        function evaluateCode() {
            const code = document.getElementById('codeInput').value;
            const consoleDiv = document.getElementById('console');
            consoleDiv.innerHTML = '';

            // Custom console.log function to output to the console div
            const originalConsoleLog = console.log;
            console.log = function(...args) {
                args.forEach(arg => {
                    const output = document.createElement('div');
                    output.textContent = typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg;
                    consoleDiv.appendChild(output);
                });
                originalConsoleLog.apply(console, args);
            };

            try {
                eval(code);
            } catch (error) {
                const errorOutput = document.createElement('div');
                errorOutput.textContent = error;
                errorOutput.style.color = 'red';
                consoleDiv.appendChild(errorOutput);
            }

            // Restore browser's console.log
            console.log = originalConsoleLog;
        }

        function downloadCodeAndEditor() {
            const codeInput = document.getElementById('codeInput').value;
            const htmlContent = document.documentElement.outerHTML.replace(
                /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
                `<textarea id="codeInput">${codeInput}</textarea>`
            );

            const blob = new Blob([htmlContent], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'code_editor.html';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function shareCode() {
            const code = document.getElementById('codeInput').value;
            const encodedCode = btoa(encodeURIComponent(code));
            window.location.hash = encodedCode;
            window.prompt("Copy the URL to share.\nBe warned! Very long URLs don't share wicked well, sometimes.", window.location.href);
        }

        function clearEverything() {
            if (!confirm('Are you sure you want to reset the playground?')) {
                return;
            } else {               
                window.location.hash = '';
                window.location.reload();
            }
        }

        function loadCodeFromHash() {
            const hash = window.location.hash.substring(1);
            if (hash) {
                try {
                    const decodedCode = decodeURIComponent(atob(hash));
                    document.getElementById('codeInput').value = decodedCode;
                } catch (error) {
                    console.error('Failed to decode the URL hash:', error);
                }
            }
        }

        function help() {
            const helpText = `
            Welcome to the JavaScript Playground! Here are some tips to get you started:

            1. Enter your JavaScript code in the textarea.
            2. Click the "Run Code" button to execute your code.
            3. The console output will be displayed below the textarea.
            4. Click the "Clear" button to reset the playground.
            5. Click the "Download" button to save your code and editor as an HTML file.
            6. Click the "Share" button to generate a URL to share your code with others.
            7. You can also press "Cmd + Enter" to run your code.
            8. There's an empty div above the buttons with the id "playground"
            9. You can mount stuff to it using the "mount" function, for more info run "mountHelp()"
            10. You can use the "clear()" function to clear the content's of the console.

            Go nuts! Share scrappy fiddles!
            `;
            console.log(helpText);
        }

        function clear() {
            document.getElementById('console').innerHTML = '';
        }

        function mountHelp() {
            console.log(`
            The mount function is used to mount stuff to the playground div.
            It takes a function as an argument, which in turn receives the playground div as an argument.
            Before mounting, it clears the playground div.
            Here's an example of how to use the mount function:

            mount(playground => {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hell is empty and all the devils are here.';
                playground.appendChild(h1);
            });

            This will add an h1 element to the playground div.
            `);
        }

        function mount(mountFunction) {
            const playground = document.getElementById('playground');
            if (!playground) {
                console.error("Couldn't find a div with the id 'playground'! You may need to reload the page.");
                return;
            }

            if (playground.innerHTML.trim() !== "") {
                playground.innerHTML = "";
            }
            mountFunction(playground);
        }


        document.getElementById('codeInput').addEventListener('keydown', function(event) {
            if (event.metaKey && event.key === 'Enter') {
                event.preventDefault();
                evaluateCode();
            }
        });

        window.onload = loadCodeFromHash;
    </script>


</body></html> vs 'abcd'");</textarea>
    <div id="console"></div>

    <script>
        function evaluateCode() {
            const code = document.getElementById('codeInput').value;
            const consoleDiv = document.getElementById('console');
            consoleDiv.innerHTML = '';

            // Custom console.log function to output to the console div
            const originalConsoleLog = console.log;
            console.log = function(...args) {
                args.forEach(arg => {
                    const output = document.createElement('div');
                    output.textContent = typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg;
                    consoleDiv.appendChild(output);
                });
                originalConsoleLog.apply(console, args);
            };

            try {
                eval(code);
            } catch (error) {
                const errorOutput = document.createElement('div');
                errorOutput.textContent = error;
                errorOutput.style.color = 'red';
                consoleDiv.appendChild(errorOutput);
            }

            // Restore browser's console.log
            console.log = originalConsoleLog;
        }

        function downloadCodeAndEditor() {
            const codeInput = document.getElementById('codeInput').value;
            const htmlContent = document.documentElement.outerHTML.replace(
                /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
                `<textarea id="codeInput">${codeInput}</textarea>`
            );

            const blob = new Blob([htmlContent], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'code_editor.html';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function shareCode() {
            const code = document.getElementById('codeInput').value;
            const encodedCode = btoa(encodeURIComponent(code));
            window.location.hash = encodedCode;
            window.prompt("Copy the URL to share.\nBe warned! Very long URLs don't share wicked well, sometimes.", window.location.href);
        }

        function clearEverything() {
            if (!confirm('Are you sure you want to reset the playground?')) {
                return;
            } else {               
                window.location.hash = '';
                window.location.reload();
            }
        }

        function loadCodeFromHash() {
            const hash = window.location.hash.substring(1);
            if (hash) {
                try {
                    const decodedCode = decodeURIComponent(atob(hash));
                    document.getElementById('codeInput').value = decodedCode;
                } catch (error) {
                    console.error('Failed to decode the URL hash:', error);
                }
            }
        }

        function help() {
            const helpText = `
            Welcome to the JavaScript Playground! Here are some tips to get you started:

            1. Enter your JavaScript code in the textarea.
            2. Click the "Run Code" button to execute your code.
            3. The console output will be displayed below the textarea.
            4. Click the "Clear" button to reset the playground.
            5. Click the "Download" button to save your code and editor as an HTML file.
            6. Click the "Share" button to generate a URL to share your code with others.
            7. You can also press "Cmd + Enter" to run your code.
            8. There's an empty div above the buttons with the id "playground"
            9. You can mount stuff to it using the "mount" function, for more info run "mountHelp()"
            10. You can use the "clear()" function to clear the content's of the console.

            Go nuts! Share scrappy fiddles!
            `;
            console.log(helpText);
        }

        function clear() {
            document.getElementById('console').innerHTML = '';
        }

        function mountHelp() {
            console.log(`
            The mount function is used to mount stuff to the playground div.
            It takes a function as an argument, which in turn receives the playground div as an argument.
            Before mounting, it clears the playground div.
            Here's an example of how to use the mount function:

            mount(playground => {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hell is empty and all the devils are here.';
                playground.appendChild(h1);
            });

            This will add an h1 element to the playground div.
            `);
        }

        function mount(mountFunction) {
            const playground = document.getElementById('playground');
            if (!playground) {
                console.error("Couldn't find a div with the id 'playground'! You may need to reload the page.");
                return;
            }

            if (playground.innerHTML.trim() !== "") {
                playground.innerHTML = "";
            }
            mountFunction(playground);
        }


        document.getElementById('codeInput').addEventListener('keydown', function(event) {
            if (event.metaKey && event.key === 'Enter') {
                event.preventDefault();
                evaluateCode();
            }
        });

        window.onload = loadCodeFromHash;
    </script>


</body></html>