首頁 > web前端 > js教程 > OpenAI 在簡化程式碼方面出奇地好

OpenAI 在簡化程式碼方面出奇地好

WBOY
發布: 2024-08-30 18:39:51
原創
1122 人瀏覽過

在瀏覽網路尋找靈感時,我發現了一個看起來很有趣的元件。

OpenAI is shockingly good at unminifying code

我認為帶有運行 ASCII 藝術的區塊看起來很酷,但我不太明白它是如何實現的,所以我開始查看原始程式碼。

我發現程式碼看起來可能可以完成這項工作,但它被縮小了。

const { floor: ra, abs: KE, min: QE } = Math,
    O5 = ["reactive.network REACTIVE.NETWORK", "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,^`'. .:â–‘â–’â–“â–ˆ"],
    G7 = Date.now() % 3 ? O5[1] : O5[0],
    V5 = G7.length,
    JE = { fps: 60 };
function eT(e, t, n, r) {
    const i = t.time * 8e-5,
        s = QE(t.cols, t.rows),
        o = t.metrics.aspect * 0.2,
        l = { x: ((4 * (e.x - t.cols / 6.25)) / s) * o, y: (5 * (e.y - t.rows / 4)) / s },
        u = ra(KE(YE(l) - i) * V5 + (ra(e.x / 1) % 2) * 2) % V5;
    return G7[u];
}
const tT = () => {
    const e = j.useRef(null),
        [t, n] = j.useState({ height: null, width: null });
    return (
        j.useEffect(() => {
            function r() {
                n({ height: window.innerHeight, width: window.innerWidth });
            }
            if (typeof window < "u") return n({ height: window.innerHeight, width: window.innerWidth }), window.addEventListener("resize", r), () => window.removeEventListener("resize", r);
        }, []),
        j.useEffect(() => {
            const r = e.current;
            if (!r) return;
            const i = 12,
                s = ra(t.width / i) * 1.6,
                o = ra(t.height / i),
                l = { aspect: s / o },
                u = setInterval(() => {
                    let c = "";
                    for (let d = 0; d < o; d++) {
                        for (let f = 0; f < s; f++) c += eT({ x: f, y: d }, { cols: s, rows: o, metrics: l, time: Date.now() });
                        c += `
`;
                    }
                    r.textContent = c;
                }, 1e3 / JE.fps);
            return () => clearInterval(u);
        }, [t]),
        a.jsx("div", { style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }, children: a.jsx("div", { ref: e, style: { width: "100%", height: "100%", whiteSpace: "pre", overflow: "hidden" } }) })
    );
};
function nT(e) {
    return Math.cos(e.x * e.x - e.y * e.y);
}
const { floor: ia, abs: rT, min: iT } = Math,
    D5 = ["reactive.network REACTIVE.NETWORK", "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,^`'. .:â–‘â–’â–“â–ˆ"],
    X7 = Date.now() % 3 ? D5[1] : D5[0],
    F5 = X7.length,
    sT = { fps: 60 };
function oT(e, t, n, r) {
    const i = t.time * 8e-5,
        s = iT(t.cols, t.rows),
        o = t.metrics.aspect * 0.2,
        l = { x: ((4 * (e.x - t.cols / 6.25)) / s) * o, y: (5 * (e.y - t.rows / 4)) / s },
        u = ia(rT(nT(l) - i) * F5 + (ia(e.x / 1) % 2) * 2) % F5;
    return X7[u];
}
const aT = () => {
    const e = j.useRef(null),
        [t, n] = j.useState({ height: null, width: null });
    return (
        j.useEffect(() => {
            function r() {
                n({ height: window.innerHeight, width: window.innerWidth });
            }
            if (typeof window < "u") return n({ height: window.innerHeight, width: window.innerWidth }), window.addEventListener("resize", r), () => window.removeEventListener("resize", r);
        }, []),
        j.useEffect(() => {
            const r = e.current;
            if (!r) return;
            const i = 12,
                s = ia(t.width / i) * 1.6,
                o = ia(t.height / i),
                l = { aspect: s / o },
                u = setInterval(() => {
                    let c = "";
                    for (let d = 0; d < o; d++) {
                        for (let f = 0; f < s; f++) c += oT({ x: f, y: d }, { cols: s, rows: o, metrics: l, time: Date.now() });
                        c += `
`;
                    }
                    r.textContent = c;
                }, 1e3 / sT.fps);
            return () => clearInterval(u);
        }, [t]),
        a.jsx("div", { style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }, children: a.jsx("div", { ref: e, style: { width: "100%", height: "100%", whiteSpace: "pre", overflow: "hidden" } }) })
    );
},
登入後複製

通常,我只是透過閱讀最小化的程式碼來了解實作(或尋找 .map 檔案來恢復原始程式碼)。然而,我意識到我從未嘗試過要求 ChatGPT 為我做這件事......所以我複製了上述所有代碼並要求 ChatGPT “解釋代碼”。回覆如下:

提供的程式碼非常複雜,但我會將其分解為更易於理解的格式,解釋其不同部分及其功能。

概述

程式碼使用 JavaScript 定義了多個函數和元件,特別是在 React 應用程式的上下文中。它涉及生成一些動態文字內容,大概是 ASCII 藝術或使用預定義集中的字元的某種視覺效果。此外,它還包括用於事件處理、效能計時和 HTML 內容轉換的實用函數。

關鍵部件和功能

  1. 字元集選擇:


``javascript
const { Floor: ra, abs: KE, min: QE } = Math;
const O5 = ["reactive.network REACTIVE.NETWORK", "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~i!lI;:,^'. . :â –'â–'â–「â–ˆ」];
const G7 = Date.now() % 3 ? O5[1] : O5[0];
const V5 = G7.length;


   - This part of the code imports some common Math functions (`floor`, `abs`, and `min`) and defines two sets of characters, stored in `O5`. 
   - Based on the current time (`Date.now() % 3`), it selects one of these sets (`G7`) to use later.
   - The length of the selected character set is stored in `V5`.

2. **Dynamic Character Selection Function:**


    ```javascript
   function eT(e, t, n, r) {
       const i = t.time * 8e-5;
       const s = QE(t.cols, t.rows);
       const o = t.metrics.aspect * 0.2;
       const l = { x: ((4 * (e.x - t.cols / 6.25)) / s) * o, y: (5 * (e.y - t.rows / 4)) / s };
       const u = ra(KE(YE(l) - i) * V5 + (ra(e.x / 1) % 2) * 2) % V5;
       return G7[u];
   }
登入後複製
  • eT 函數根據輸入位置 (e.x, e.y) 和當前時間 (t.time) 產生字元。
  • 它使用一些長寬比計算來調整位置,並根據位置和時間的組合從 G7 中選擇一個角色。
  • YE 函數的用途並不能從程式碼中直接看出,但它似乎是此計算中使用的自訂函數。
  1. 用於顯示動態內容的 React 元件 (tT):


```javascript
const tT = () =>; {
const e = j.useRef(null);
const [t, n] = j.useState({ height: null, width: null });
j.useEffect(() => {
函數 r() {
n({ 高度: window.innerHeight, 寬度: window.innerWidth });
}
if (typeof window < "u") {
n({ 高度: window.innerHeight, 寬度: window.innerWidth });
window.addEventListener("調整大小", r);
返回() => window.removeEventListener("resize", r);
}
}, []);

   j.useEffect(() => {
       const r = e.current;
       if (!r) return;
       const i = 12;
       const s = ra(t.width / i) * 1.6;
       const o = ra(t.height / i);
       const l = { aspect: s / o };
       const u = setInterval(() => {
           let c = "";
           for (let d = 0; d < o; d++) {
               for (let f = 0; f < s; f++) c += eT({ x: f, y: d }, { cols: s, rows: o, metrics: l, time: Date.now() });
               c += `
登入後複製

`;
}
r.textContent = c;
}, 1e3 / JE.fps);
返回() =>清除間隔(u);
}, [t]);

   return a.jsx("div", { style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }, children: a.jsx("div", { ref: e, style: { width: "100%", height: "100%", whiteSpace: "pre", overflow: "hidden" } }) });
登入後複製

};


   - This is a React component that sets up an interval to periodically update the content of a `div` element (`e.current`) with dynamically generated characters.
   - It calculates the number of columns (`s`) and rows (`o`) based on the window size and then fills the `div` with characters generated by the `eT` function.
   - The effect runs at a specified frames per second (`JE.fps`).
登入後複製

我隨後要求“在 TypeScript 中實現等效程式碼並使其易於閱讀”,並得到以下答案:

import React, { useEffect, useRef, useState } from 'react';

const selectedCharacterSet =
  "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,^`'. .:â–‘â–’â–“â–ˆ";
const characterSetLength = selectedCharacterSet.length;

const calculateCharacter = (
  x: number,
  y: number,
  cols: number,
  rows: number,
  aspect: number,
  time: number,
): string => {
  const timeFactor = time * 0.000_08;
  const size = Math.min(cols, rows);
  const aspectRatio = aspect * 0.2;
  const position = {
    x: ((4 * (x - cols / 6.25)) / size) * aspectRatio,
    y: (5 * (y - rows / 4)) / size,
  };

  const index =
    Math.floor(
      Math.abs(
        Math.cos(position.x * position.x - position.y * position.y) -
          timeFactor,
      ) *
        characterSetLength +
        (Math.floor(x) % 2) * 2,
    ) % characterSetLength;
  return selectedCharacterSet[index];
};

type Size = {
  height: null | number;
  width: null | number;
};

const AsciiArtGenerator: React.FC = () => {
  const textRef = useRef<HTMLDivElement>(null);
  const [size, setSize] = useState<Size>({ height: null, width: null });

  useEffect(() => {
    const handleResize = () => {
      setSize({ height: window.innerHeight, width: window.innerWidth });
    };

    // Initial size setting
    handleResize();

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  useEffect(() => {
    const element = textRef.current;
    if (!element || !size.width || !size.height) return undefined;

    const cols = Math.floor(size.width / 12) * 1.6;
    const rows = Math.floor(size.height / 12);
    const aspectRatio = cols / rows;

    const intervalId = setInterval(() => {
      let content = '';

      for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
          content += calculateCharacter(
            x,
            y,
            cols,
            rows,
            aspectRatio,
            Date.now(),
          );
        }

        content += '\n';
      }

      element.textContent = content;
    }, 1_000 / 60); // 60 fps

    return () => {
      clearInterval(intervalId);
    };
  }, [size]);

  return (
    <div
      ref={textRef}
      style={{
        height: '100%',
        overflow: 'hidden',
        whiteSpace: 'pre',
        width: '100%',
      }}
    />
  );
};

export default () => {
  return <AsciiArtGenerator />;
};
登入後複製

令我驚訝的是,回覆不僅夠好,而且可讀性也很強。

這是上面的組件的實際應用。

比較輸出,看起來 LLM 回應忽略了一些實作細節,但它仍然是一個足夠好的實作可供學習。這絕對是我以前從未考慮過的巧妙用例!

以上是OpenAI 在簡化程式碼方面出奇地好的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板