javascript - JQuery - Swapping two elements does not work after first move -


i have function bubble sort among content of various divs. each swap operation, swaps divs too, using jquery swapsies plugin. problem tht swap once, , after other swap operations:

function swap(id1, id2){  $('#' +id1).swap({   target: id2,   opacity: "0.5",   speed: 1000,   callback: function() {     } });  }  function bubblesort() {  var ret=[]; $(".num-div").each(function(){ ret.push($(this));});  let swapped; {   swapped = false;   (let = 1; < ret.length; ++i) {      if (ret[i - 1].html() > ret[i].html()) {       swap(ret[i-1].attr('id'), ret[i].attr('id'));       [ret[i], ret[i - 1]] = [ret[i - 1], ret[i]];        swapped = true;      }   } } while (swapped); return ret; 

}

in first step i=1 works , swaps ret[i-1] ret[i], after not work.

the swap plug-in not process calls when busy animation. can see in source code of plug-in:

if (options.target!="" && !swapping) { 

the swapping variable true during ongoing animation, , if skip new animation without notice.

anyway, want animations happen in sequence, not @ same time. purpose suggest using promises , rather new async/await syntax.

first promisify swap function, returns promise. add async , await keywords @ appropriate spot, , ... work.

one more caution: if data numerical, , want sort numeric value, need convert strings numbers before doing comparison, instance applying unary + this: +ret[i].text()

here working demo:

function swap(id1, id2){      return new promise(resolve =>           $('#' +id1).swap({            target: id2,            opacity: "0.5",            speed: 500,            callback: resolve          })      );  }    async function bubblesort() {      var ret=[];      $(".num-div").each(function(){           ret.push($(this));      });        let swapped;      {          swapped = false;          (let = 1; < ret.length; ++i) {              if (ret[i - 1].text() > ret[i].text()) {                  await swap(ret[i-1].attr('id'), ret[i].attr('id'));                  [ret[i], ret[i - 1]] = [ret[i - 1], ret[i]];                  swapped = true;              }          }      } while (swapped);      return ret;  }    bubblesort().then( ret => {      console.log($.map(ret, x => $(x).text()));  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="http://biostall.com/wp-content/uploads/2010/07/jquery-swapsies.js"></script>  <div id="i1" class="num-div">sort</div>  <div id="i2" class="num-div">these</div>  <div id="i3" class="num-div">words</div>  <div id="i4" class="num-div">in</div>  <div id="i5" class="num-div">alphabetical</div>  <div id="i6" class="num-div">order</div>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -