Greasy Fork

Basic Math Solver

A simple calculator for addition, subtraction, and multiplication that floats on any webpage.

目前为 2024-11-23 提交的版本。查看 最新版本

// ==UserScript==
// @version 0.2
// @name         Basic Math Solver
// @namespace    https://example.com
// @description  A simple calculator for addition, subtraction, and multiplication that floats on any webpage.
// @author       nukerboss
// @match         http://live.mathletics.com/*
// @match        *://live.mathletics.com/*
// @grant        none
// ==/UserScript==
// @license MIT
(function() {
    'use strict';

    // Listen for the "A" key press
    document.addEventListener('keydown', function (event) {
        if (event.key.toLowerCase() === 'a') {
            solveMathProblems();
        }
    });

    function solveMathProblems() {
        // Get all text nodes from the webpage
        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
        let node;
        const mathRegex = /(\d+)\s*([\+\-\*\/])\s*(\d+)/; // Match simple math problems like "5 + 3"

        while ((node = walker.nextNode())) {
            const text = node.nodeValue;

            // Check if the text contains a math problem
            const match = text.match(mathRegex);
            if (match) {
                const num1 = parseFloat(match[1]);
                const operator = match[2];
                const num2 = parseFloat(match[3]);

                let result;
                switch (operator) {
                    case '+':
                        result = num1 + num2;
                        break;
                    case '-':
                        result = num1 - num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    case '/':
                        result = num1 / num2;
                        break;
                    default:
                        result = 'Error';
                }

                // Append the result next to the math problem
                const parent = node.parentNode;
                if (parent) {
                    parent.innerHTML = parent.innerHTML.replace(
                        text,
                        `${text} = <strong>${result}</strong>`
                    );
                }
            }
        }
    }
})();