简体   繁体   中英

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. However, I want to be able to access my i and j variables outside of the function. I am attempting to do this by declaring them outside of the function, passing them in, and returning them after each match. 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.

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

 const nextMatch = () => { naive(text, pat, i, j).then((results) => { updateI(results[0]); updateJ(results[1]); }); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM