Giter Club home page Giter Club logo

adtyavrdhn / sorting-visualizer-react- Goto Github PK

View Code? Open in Web Editor NEW
3.0 1.0 0.0 395 KB

Sorting Visualizer is an algorithm visualizing tool built to visualize the difference betweeen common sorting algorithms. It is built using React,TypeScript and Tailwind CSS.

Home Page: https://sorting-visualizer-adtyavrdhn.vercel.app/

HTML 11.94% CSS 1.55% TypeScript 84.86% JavaScript 1.65%
immer immerjs react reactjs sorting-algorithm-visualizations sorting-algorithms sorting-visualization tailwindcss

sorting-visualizer-react-'s Introduction

Title: Sorting Visualizer

Sorting Visualizer is an algorithm visualizing tool built to visualize the difference betweeen common sorting algorithms. It is built using React,TypeScript and Tailwind CSS.

You can try it out the following URL Live : https://sorting-visualizer-adtyavrdhn.vercel.app/

sorting-visualizer-react-'s People

Contributors

adtyavrdhn avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

sorting-visualizer-react-'s Issues

Review: SortBtn

interface Sort { // rename to SortButtonProps
  sortingAlgo: string;
  arr: number[];
  towers: JSX.Element[];
  HandleChange: Function;
  trace: number[][];
  sort: Function;
  setAlgo: Function;
}

Only the sort and sortingAlgo props are used by the button, remove other props

function SortBtn(props: any) {
  return <button onClick={props.sort}>{props.sortingAlgo} Sort</button>;
}

This requires you to call event.target.innerHTML in the onClick handler. Instead you should just do the following

function SortButton(props: any) { // rename to SortButton
  return <button onClick={() => props.sort(props.sortingAlgo)}>{props.sortingAlgo} Sort</button>;
}

Also replace any with SortProps

Review: App.tsx

const everywhere

In most cases you should be able to just use const for all variables so avoid using let

arr state

We should not be maintaining state outside of react components in global like variables like this:

let arr: number[] = [];

First off we will start by managing arr in react component state, so start by uncommenting line 17

// const [arr, setArr] = useState([0]);

initializing arr

function initarr() {
  // setArr([]);
  arr = [];
  while (arr.length < sizeValue) {
    var r = Math.floor(Math.random() * 100) + 50;
    if (arr.indexOf(r) === -1) arr.push(r);
  }
  initTowers();
}

useEffect(() => {
  initarr();
}, [sizeValue]);

Move the code of initArr function inside useEffect and then instead of calling initTowers use setArr. Example:

useEffect(() => {
  const newArr = []; // declare new const arr and not mutate existing variables
  while (newArr.length < sizeValue) {
    // code
  }
 setArr(newArr);
}, [sizeValue]);

Send setArr to sorting functions instead of initTowers

Instead of sorting algorithms calling initTowers function let them set the updated arr using setArr

bubbleSort(arr, initTowers);

// change to

bubbleSort(arr, setArr);

Move the logic of initTowers into a useEffect to reset towers whenever arr changes

function initTowers() {
  let temptowers: JSX.Element[] = arr.map((n: number, index: number) => (
    <div
      className={"bg-black tower"}
      key={index}
      style={{ height: `${n / 7}rem` }}
    ></div>
  ));
  setTowers(temptowers);
}

becomes

useEffect(() => {
  const temptowers: JSX.Element[] = arr.map((n: number, index: number) => (
    <div
      className={"bg-black tower"}
      key={index}
      style={{ height: `${n / 7}rem` }}
    ></div>
  ));
  setTowers(temptowers);
}, [arr, temptowers]);

This will ensure that the towers always update when arr changes

Review: RangeSlider

function RangeSlider(props: any) {
  return (
    <div className="RangeSlider flex justify-center">
      <label htmlFor="size" className="size mr-2 mt-0.2">
        {props.type}
      </label>
      <input
        className={props.type + "-range"}
        min={props.minimum}
        max={props.maximum}
        type="range"
        name={props.type}
        id={props.type + "-slider"}
        step={props.step}
        value={props.value}
        disabled={props.disabled}
        onChange={(event: any) => props.setVal(event.target.value)}
      />
    </div>
  );
}
  1. Rename props.type to props.name
  2. Remove unused className prop
  3. Remove unused id prop (most often than not you should not need an id prop)
function RangeSlider(props: any) {}

// prefer destructuring props as below

function RangeSlider({ name, max, min, step, value, disabled, setValue }: any) {
    // inside the code then you need not refer to each item as `props.`
}

Review: App.tsx (Part 2)

Eliminate 'towers' state variable

We no longer need the following useEffect (L59),

useEffect(() => {
  const temptowers: JSX.Element[] = arr.map((n: number, index: number) => (
    <div
      className={
        "bg-gradient-to-b from-indigo-500 via-purple-500 to-pink-500 rounded-md"
      }
      key={index}
      style={{ height: `${n / 7}rem`, width: `0.7%` }}
    ></div>
  ));
  setTowers(temptowers);
}, [arr]);

Instead Inline the arr.map((n: number, index: number) => ( code onto line 93 <div className="flex mt-3 gap-1.5 justify-center">{towers}</div>

Review: Towers.tsx

Eliminate towers state variable

Any variable that is derived based on a prop or a state variable should not be created as another state variable, you can use it directly in the render output, see illustration below

Remove the following lines of code

const [towers, setTowers] = useState<JSX.Element[]>([]); // Line 17
useEffect(() => { // Line 65 - 76
  const temptowers: JSX.Element[] = narr.map((n: number, index: number) => (
    <div
      className={
        "bg-gradient-to-b from-indigo-500 via-purple-500 to-pink-500 rounded-md"
      }
      key={index}
      style={{ height: `${n / 10}rem`, width: `0.7%` }}
    ></div>
  ));
  setTowers(temptowers);
}, [narr]);

Update the following lines of code

Before update

// Line 78 - 84
return (
  <div className="grid lg:gap-3 mt-1">
    <SortBtn sortingAlgo={props.algo} sort={sort}></SortBtn>
    <div className="flex gap-0.5 mt-1 justify-center">{towers}</div>
    <span className="text-center">Time Taken: {time}</span>
  </div>
);

After udpate

return (
  <div className="grid lg:gap-3 mt-1">
    <SortBtn sortingAlgo={props.algo} sort={sort}></SortBtn>
    <div className="flex gap-0.5 mt-1 justify-center">
      {narr.map((n: number, index: number) => (
        <div
          className={
            "bg-gradient-to-b from-indigo-500 via-purple-500 to-pink-500 rounded-md"
          }
          key={index}
          style={{ height: `${n / 10}rem`, width: `0.7%` }}
        />
      ))}
    </div>
    <span className="text-center">Time Taken: {time}</span>
  </div>
);

Extract Sorts enum outside of towers component and use in App.tsx also

Move the sorts enum outside of Towers function and export it. Once exported use this enum in App.tsx

App.tsx before update

// Line 32
<Towers arr={[...arr]} algo={"Bubble Sort"} speed={speed}></Towers>

App.tsx after update

// Line 32
<Towers arr={arr} algo={Sorts.Bubble} speed={speed}></Towers>

Do not use array spread operator excessively [...arr]

In both App.tsx and Towers.tsx in a lot of places we use [...arr] or [...narr] - the only place we should use array spread is inside the sorting algorithms when calling setArr or setNarr

On Immer Usage (non critical)

Immer is not being leveraged correctly here, the produce function should be used inside the sort functions - where produce should replace the [...arr]

Button click feedback

Clicking buttons does not provide any 'clicky' feedback, can we do some active css pseudo class styling using tailwind to make the buttons feel like buttons

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.