vuejs2chart.jschartkick

How to make dynamic chart using Vue component with chart-js


I am making Bubble sort visualization algorithm and wanted to show to the process of shorting using line graph.

I have tried to implement the computed property but the browser hangs.

<template>
  <div class="hello">
    <h1>Bubble Sort</h1>
    <p>{{ bubbleSort()}}</p>
    <line-chart :data="bubbleSort()"></line-chart>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      a : [12, 0, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213] 
    }
  },
  methods : {
    bubbleSort: function () {
      let swapped;
      do {
        swapped = false;
        for(var i = 0; i < this.a.length; i++){
          if(this.a[i] > this.a[i+1]){
            let temp = this.a[i];
            this.a[i] = this.a[i+1];
            this.a[i+1] = temp;
            swapped = true;
          }
        }
      }while(swapped);
      return Object.assign({},this.a);
    }
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>

I expect the chart to update while shorting is happening.


Solution

  • Using a computed property is not the best way to implement a bubble sort visualization, for two reasons:

    Since you are not using a directly in your template, and the computed property has only one dependency, a, get rid of the computed property, it's not needed.

    Instead, create a function that completes a single pass of the bubble sort algorithm, and call that function in a setInterval, cancelling the loop when a pass is made with 0 swaps:

    export default {
      name: 'HelloWorld',
      data() {
        return {
          a : [12, 0, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213],
          intervalId: null,
        }
      },
      methods: {
        bubbleSort() {
          let swapped = false;
    
          for (let i = 0; i < this.a.length - 1; i++) {
            if (this.a[i] > this.a[i+1]) {
              const temp = this.a[i];
              this.$set(this.a, i, this.a[i+1]);
              this.$set(this.a, i+1, temp);
              swapped = true;
            }
          }
    
          if (!swapped) {
            clearInterval(this.intervalId);
          }
        },
      },
      mounted() {
        this.intervalId = setInterval(() => {
          this.bubbleSort();
        }, 2000);
      }
    };
    

    Notes: