首页 > web前端 > js教程 > 正文

OpenAI 在简化代码方面出奇地好

WBOY
发布: 2024-08-30 18:39:36
原创
312 人浏览过

在浏览互联网寻找灵感时,我发现了一个看起来很有趣的组件。

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("resize", 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!