Skip to content

Commit

Permalink
♻️ 重写for和forEach为map
Browse files Browse the repository at this point in the history
  • Loading branch information
neila-a committed Jun 8, 2024
1 parent 1edf2a3 commit 3b05362
Show file tree
Hide file tree
Showing 15 changed files with 75 additions and 103 deletions.
18 changes: 4 additions & 14 deletions packages/core/prebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,12 @@ async function devMain() {
return oldPackage;
}
async function publicMain() {
const pages = ChildProcess.execSync(`find ./src/app -name '*page.tsx'`).toString().replaceAll("./src/app", "").replaceAll("page.tsx", "").split("\n");
pages.forEach((single, index) => {
const pages = ChildProcess.execSync(`find ./src/app -name '*page.tsx'`).toString().replaceAll("./src/app", "").replaceAll("page.tsx", "").split("\n").map(single => {
if (single !== "/") {
pages[index] = pages[index].substr(0, pages[index].length - 1);
return single.substr(0, single.length - 1);
}
});
pages.forEach((single, index) => {
if (single === "/handle") {
pages.splice(index, 1);
}
});
pages.forEach((single, index) => {
if (single === "") {
pages.splice(index, 1);
}
});
return "/";
}).filter(single => single !== "");
const pagesJSON = JSON.stringify(pages, null, 4);
fs.writeFileSync("./src/pages.json", pagesJSON);
const NextConfig = await build({
Expand Down
10 changes: 4 additions & 6 deletions packages/core/src/app/index/sidebar/searchBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import {
tool
} from "tools/info";
export default function searchBase(sortedTools: tool[], search: string) {
const calcTools: tool[] = [],
lower = String(search).toLowerCase();
sortedTools.forEach(tool => {
const lower = String(search).toLowerCase();
return sortedTools.filter(tool => {
const to = String(tool.to);
if (tool.desc.toLowerCase().includes(lower) || to.includes(search) || tool.name.toLowerCase().includes(lower)) calcTools.push(tool);
});
return calcTools;
return tool.desc.toLowerCase().includes(lower) || to.includes(search) || tool.name.toLowerCase().includes(lower);
})
}
5 changes: 0 additions & 5 deletions packages/shared/Recently.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ export default class Recently extends Set<string> {
super.add(name);
}
if (super.size > this.max) {
this.get().forEach((item, index) => {
if (index === 0) {
super.delete(item);
}
});
super.delete(this.get()[0]);
}
return this;
Expand Down
9 changes: 5 additions & 4 deletions packages/shared/matrix/base.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Palette
} from "@mui/material";
import range from "../range";
import {
block
} from "./matrix";
Expand All @@ -24,8 +25,8 @@ export default function drawMatrixBase(edge: number, n: number, blocks: block[],
dos.forEach((item, index) => {
cxt.fillStyle = item[1];
const path = new Path2D(), pBlock = item[0].map(item => item.toString());
for (let i = 0; i <= n; i++) {
for (let j = 0; j < n; j++) {
for (let i of range(n)) {
for (let j of range(n)) {
if (pBlock.includes([i, j].toString())) {
path.rect(size * j, size * i, size, size);
}
Expand All @@ -34,8 +35,8 @@ export default function drawMatrixBase(edge: number, n: number, blocks: block[],
cxt.fill(path);
});
if (!onlyPos) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
for (let i of range(n - 1)) {
for (let j of range(n - 1)) {
cxt.rect(size * j, size * i, size, size);
}
}
Expand Down
5 changes: 5 additions & 0 deletions packages/shared/range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default function* range(top: number, initial: number = 0) {
for (let i = initial; i <= top; i++) {
yield i;
}
}
9 changes: 5 additions & 4 deletions packages/tools/tool-cylinder/makeCylinder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
block
} from "@verkfi/shared/matrix/matrix";
import range from "@verkfi/shared/range";
/**
* 生成一个圆。
* ![cylinder](./cylinder.png)
Expand Down Expand Up @@ -35,15 +36,15 @@ export default class Cylinder extends Array<block> {
let nextMinXn = 0;
const minInvRadiusX = 1 / (radiusX - thickness),
minInvRadiusZ = 1 / (radiusZ - thickness);
forX: for (let x = 0; x <= ceilRadiusX; ++x) {
forX: for (let x of range(ceilRadiusX)) {
const xn = nextXn,
dx2 = nextMinXn * nextMinXn;
nextXn = (x + 1) * invRadiusX;
nextMinXn = (x + 1) * minInvRadiusX;
let nextZn = 0,
nextMinZn = 0;
xSqr = xn * xn;
forZ: for (let z = 0; z <= ceilRadiusZ; ++z) {
for (let z of range(ceilRadiusZ)) {
const zn = nextZn,
dz2 = nextMinZn * nextMinZn;
nextZn = (z + 1) * invRadiusZ;
Expand All @@ -63,12 +64,12 @@ export default class Cylinder extends Array<block> {
}
}
} else {
forX: for (let x = 0; x <= ceilRadiusX; ++x) {
forX: for (let x of range(ceilRadiusX)) {
const xn = nextXn;
nextXn = (x + 1) * invRadiusX;
let nextZn = 0;
xSqr = xn * xn;
forZ: for (let z = 0; z <= ceilRadiusZ; ++z) {
for (let z of range(ceilRadiusZ)) {
const zn = nextZn;
nextZn = (z + 1) * invRadiusZ;
zSqr = zn * zn;
Expand Down
5 changes: 3 additions & 2 deletions packages/tools/tool-jigsaw/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
} from "react-intl-universal";
import useStoragedState from "@verkfi/shared/reader/useStoragedState";
import canvasToBlob from "./canvasToBlob";
import range from "@verkfi/shared/range";
type block = Blob & {
rotation: number;
};
Expand Down Expand Up @@ -116,9 +117,9 @@ export default function JigsawEntry(): JSX.Element {
splited: Blob[][] = [];
canvas.width = img.width / width;
canvas.height = img.height / height;
for (let y = 0; y < height; y++) {
for (let y of range(height - 1)) {
const thisBuffer: Blob[] = [];
for (let x = 0; x < width; x++) {
for (let x of range(width - 1)) {
context.drawImage(img, x * img.width / width, y * img.height / height, img.width / width, img.height / height, 0, 0, img.width / width, img.height / height);
thisBuffer.push(await canvasToBlob(canvas));
context.clearRect(0, 0, img.width / width, img.height / height);
Expand Down
62 changes: 30 additions & 32 deletions packages/tools/tool-mathgen/calcMath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,37 @@ import genNumber from "./genNumber";
import {
evaluate
} from "mathjs";
export default function calcMath(calcs: calc[], subtractionCheck: boolean, divisionCheck: boolean, max: number, min: number, itemCount: number, setMath: setState<string[]>) {
const calcMaths: string[] = [];
calcs.forEach(function (mode) {
const modeS = mode.replace("×", "*").replace("÷", "/");
function genMathS(): [number, number, number] {
const one = genNumber(max, min);
let two = genNumber(max, min);
if (subtractionCheck || divisionCheck) {
switch (mode) {
case "-":
case "÷":
while (two > one) {
two = genNumber(max, min);
}
break;
default:
break;
}
import range from "@verkfi/shared/range";
const calcMath = (calcs: calc[], subtractionCheck: boolean, divisionCheck: boolean, max: number, min: number, itemCount: number, setMath: setState<string[]>) => setMath([...new Set(calcs.map(mode => {
const modeS = mode.replace("×", "*").replace("÷", "/");
function genMathS(): [number, number, number] {
const one = genNumber(max, min);
let two = genNumber(max, min);
if (subtractionCheck || divisionCheck) {
switch (mode) {
case "-":
case "÷":
while (two > one) {
two = genNumber(max, min);
}
break;
default:
break;
}
return [one, two, evaluate(`${one} ${modeS} ${two}`)];
}
for (let step = 1; step < (itemCount / (calcs.length)); step++) {
let [one, two, out] = genMathS(),
math = `${one}${mode}${two}=${out}`;
function reGenMath() {
[one, two, out] = genMathS();
math = `${one}${mode}${two}=${out}`;
}
while (out > max || calcMaths.includes(math) || (mode === "%" && two === 0)) {
reGenMath();
}
calcMaths.push(math);
return [one, two, evaluate(`${one} ${modeS} ${two}`)];
}
return [...range(itemCount / (calcs.length) - 1, 1)].map(step => {
let [one, two, out] = genMathS(),
math = `${one}${mode}${two}=${out}`;
function reGenMath() {
[one, two, out] = genMathS();
math = `${one}${mode}${two}=${out}`;
}
while (out > max || (mode === "%" && two === 0)) {
reGenMath();
}
return math;
});
return setMath(calcMaths);
}
})).keys()].flat(14)); // 14 没有什么意义
export default calcMath;
9 changes: 3 additions & 6 deletions packages/tools/tool-pi/generatePis.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
"use client";
import range from "@verkfi/shared/range";
import generateDigitsOfPi from "./generateDigitsOfPi";
export default function generatePis(digit: number) {
let ret = "3.",
generaterInstance = generateDigitsOfPi();
for (let i = 0; i < digit; i++) {
ret += (generaterInstance.next().value as number).toString();
}
return ret;
const generaterInstance = generateDigitsOfPi();
return `3.${[...range(digit - 1)].map(() => (generaterInstance.next().value as number).toString()).join("")}`;
}
1 change: 0 additions & 1 deletion packages/tools/tool-pillar/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export default function Pillar(): JSX.Element {
[length, setLength] = useState<number>(0),
[filterRules, setFilterRules] = useState(emptyFilterRules as filterRules),
choosesId = useId(),
valueSelectLabelId = useId(),
sizeLabelId = useId(),
pillars = calcPillars(type, length),
filteredPillars = pillars.filter(single => Object.entries(filterRules).every(singleRule => (
Expand Down
11 changes: 4 additions & 7 deletions packages/tools/tool-probability/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
VictoryBar,
VictoryChart
} from "victory";
import range from "@verkfi/shared/range";
export default function Probability(): JSX.Element {
const [code, setCode] = useState(`// ${get("probability.tip")}`),
theme = useTheme(),
Expand All @@ -40,7 +41,7 @@ export default function Probability(): JSX.Element {
x: any,
y: number
}[] = [];
datas.map(data => {
datas.forEach(data => {
const index = objectDatas.findIndex(objectData => objectData.x === data);
if (index === -1) {
return objectDatas.push({
Expand All @@ -63,12 +64,8 @@ export default function Probability(): JSX.Element {
{get("probability.import")}
</Button>
<Button variant="contained" onClick={event => {
const executing = new Function(code),
draft = [];
for (let i = 0; i < times; i++) {
draft[i] = executing();
}
setDatas(draft);
const executing = new Function(code);
setDatas([...range(times - 1)].map(() => executing()));
}} startIcon={(
<PlayArrow />
)}>
Expand Down
15 changes: 3 additions & 12 deletions packages/tools/tool-shaizi/Cube.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
rotateStep,
randomAxis
} from "./shaiziCanvas";
import range from "@verkfi/shared/range";
export default function Cube(props: {
cishu: number;
}) {
Expand Down Expand Up @@ -54,18 +55,8 @@ export default function Cube(props: {
<camera ref={camera} position={[10, 10, 10]} />
<mesh ref={mesh} args={[cube, materials]} onClick={event => {
if (stage.current.length === 0) {
const oldStage = [];
while (oldStage.toString() === cacheStage.current.toString()) for (let step = 0; step < props.cishu; step++) {
oldStage.push(randomAxis());
}
if (oldStage.toString() === cacheStage.current.toString()) {
oldStage.splice(0, oldStage.length);
for (let step = 0; step < props.cishu; step++) {
oldStage.push(randomAxis());
}
} else {
cacheStage.current = oldStage;
}
const oldStage = [...range(props.cishu - 1)].map(() => randomAxis());
cacheStage.current = oldStage;
stage.current = oldStage;
}
}}>
Expand Down
4 changes: 1 addition & 3 deletions packages/tools/tool-shaizi/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import {
import {
get
} from "react-intl-universal";
import {
ShaiZiCanvas
} from "./shaiziCanvas";
import ShaiZiCanvas from "./shaiziCanvas";
function ShaiZi(): JSX.Element {
const [cishu, setCishu] = useState<number>(10);
return (
Expand Down
2 changes: 1 addition & 1 deletion packages/tools/tool-shaizi/shaiziCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type rotateAxis = "x" | "y" | "z";
export const rotateAxis: rotateAxis[] = ["x", "y", "z"],
rotateStep = 50, // 转90度所需要的帧
randomAxis = () => rotateAxis[Math.floor(Math.random() * 3)];
export function ShaiZiCanvas(props: {
export default function ShaiZiCanvas(props: {
cishu: number;
}): JSX.Element {
// Use useRef hook to access the canvas element
Expand Down
13 changes: 7 additions & 6 deletions packages/tools/tool-speech/getShortTimeEnergy.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import range from "@verkfi/shared/range";

export default function getShortTimeEnergy(audioData: Float32Array) {
let sum = 0;
const energy = [];
const {
length
} = audioData;
for (let i = 0; i < length; i++) {
return [...range(length - 1)].map(i => {
sum += audioData[i] ** 2;
if ((i + 1) % 256 === 0) {
energy.push(sum);
const ret = sum;
sum = 0;
return ret;
} else if (i === length - 1) {
energy.push(sum);
return sum;
}
}
return energy;
});
}

0 comments on commit 3b05362

Please sign in to comment.