Advertisement
sapitando

mySortRecursiveFn.js

Apr 22nd, 2022 (edited)
1,102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const join = (iterable, separator = '') => {
  2.   if (iterable === undefined) return undefined;
  3.  
  4.   let str = '';
  5.  
  6.   for (let pos = 0, last = iterable.length - 1; pos <= last; pos++)
  7.     str += iterable[pos] + (pos < last ? separator : '');
  8.    
  9.   return str;
  10. };
  11.  
  12.  
  13. const recursiveSort = (function() {
  14.   let referencePoint = 0,
  15.       position,
  16.       endOfIterable,
  17.       tempArray,
  18.       sortTestFn,
  19.       typeOfReturn;
  20.  
  21.   const builtIn = (a, b) =>
  22.     typeof a === 'string' || typeof b === 'string' ? +(a > b) : a - b;
  23.    
  24.   return function innerFn(iterable, callBackFn = builtIn) {
  25.     if (referencePoint === 0) {
  26.       if (iterable === undefined) return undefined;
  27.       position = referencePoint;
  28.       endOfIterable = (tempArray = [...iterable]).length - 1;
  29.       sortTestFn = callBackFn;
  30.       typeOfReturn = typeof iterable;
  31.     }
  32.    
  33.     if (referencePoint >= endOfIterable) {
  34.       referencePoint = 0;
  35.       return typeOfReturn === 'string' ? join(tempArray) : tempArray;
  36.     }
  37.    
  38.     if (sortTestFn(tempArray[position], tempArray[position + 1]) >= 1)  {
  39.       [tempArray[position], tempArray[position + 1]] = [tempArray[position + 1], tempArray[position]];
  40.      
  41.       if (position > 0 && sortTestFn(tempArray[position - 1], tempArray[position]) >= 1) {
  42.         position--;
  43.         return innerFn();
  44.       }
  45.      
  46.     }
  47.    
  48.     position = ++referencePoint;
  49.     return innerFn();
  50.   };
  51. })();
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement