Advertisement
sapitando

MySortFn.js

Apr 23rd, 2022 (edited)
985
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function mySort(iterable, sortTestFn) {
  2.   if (!Array.isArray(iterable) && typeof iterable !== 'string') return undefined;
  3.  
  4.   const join = (iterable) => {
  5.  
  6.     let str = '';
  7.  
  8.     for (let pos = 0, last = iterable.length - 1; pos <= last; pos++)
  9.       str += iterable[pos];
  10.    
  11.     return str;
  12.   };
  13.  
  14.   let referencePoint = 0,
  15.       position = 0,
  16.       tempArray = [...iterable],
  17.       endOfIterable = tempArray.length - 1,
  18.       typeOfReturn = typeof iterable;
  19.      
  20.   if (sortTestFn === undefined)
  21.     sortTestFn = (a, b) =>
  22.       typeof a === 'string' || typeof b === 'string' ? +(a > b) : a - b;
  23.    
  24.   while (referencePoint < endOfIterable) {
  25.     if (sortTestFn(tempArray[position], tempArray[position + 1]) >= 1)  {
  26.       [tempArray[position], tempArray[position + 1]] = [tempArray[position + 1], tempArray[position]];
  27.       if (position > 0 && sortTestFn(tempArray[position - 1], tempArray[position]) >= 1) {
  28.         position--;
  29.         continue;
  30.       }
  31.     }
  32.     position = ++referencePoint;
  33.   }
  34.  
  35.   return typeOfReturn === 'string' ? join(tempArray) : tempArray;
  36. }
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement