[英]Visualising pattern matching in JavaScript
I have a naive pattern matching function, and I'm trying to slow down execution of each comparison so I can create a visualiser for it.我有一个与 function 匹配的简单模式,我正在尝试减慢每个比较的执行速度,以便为它创建一个可视化器。 However, I want to be able to access my i and j variables outside of the function.
但是,我希望能够在 function 之外访问我的 i 和 j 变量。 I am attempting to do this by declaring them outside of the function, passing them in, and returning them after each match.
我试图通过在 function 之外声明它们,将它们传入并在每场比赛后返回它们来做到这一点。 This way I can press a button to control the flow of execution.
这样我可以按一个按钮来控制执行流程。 However, they are not being returned properly, and I suspect this has something to do with my use of async/await, and the need to return the values as a Promise.
但是,它们没有正确返回,我怀疑这与我使用 async/await 有关,并且需要将值作为 Promise 返回。
https://codesandbox.io/s/staging-http-0zm04?file=/src/App.tsx:0-1072 https://codesandbox.io/s/staging-http-0zm04?file=/src/App.tsx:0-1072
import React, { useState } from "react";
import "./styles.css";
const delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));
export const naive = async (text: string, pattern: string, i: number, j: number) => {
const matches = [];
let n = text.length;
let m = pattern.length;
while (i < n){
while (j < pattern.length && pattern[j] === text[i + j]){
j += 1;
await delay(500);
}
if (j === m){
matches.push(i)
}
return [i, j, matches]
}
}
export default function App() {
const [text, setText] = useState<string>("abcdefghijklmnopqrstuvwxyzabcd")
const [pat, setPat] = useState<string>("abc")
const [i, updateI] = useState(0);
const [j, updateJ] = useState(0);
const nextMatch = () => {
let results = naive(text, pat, i, j);
updateI(results[0]);
updateJ(results[1]);
}
return (
<div>
<button style = {{width: "100px", height: "50px"}}onClick = {() => nextMatch()}/>
{i}
{j}
</div>
);
}
As navie is an async function you have to add then .This would help to return correct i and j values由于 navie 是异步 function 你必须添加then 。这将有助于返回正确的 i 和 j 值
const nextMatch = () => { naive(text, pat, i, j).then((results) => { updateI(results[0]); updateJ(results[1]); }); };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.