kstoyanov

06. * Sorted List

Oct 13th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function sortedList() {
  2.   const list = (function () {
  3.     const collection = [];
  4.  
  5.     const collectionProcessor = {
  6.       add(element) {
  7.         collection.push(element);
  8.         collection.sort(ascendingOrder);
  9.         this.size++;
  10.         return collection;
  11.       },
  12.       remove(index) {
  13.         if (isValidIndex(index)) {
  14.           collection.splice(index, 1);
  15.           this.size--;
  16.           return collection;
  17.         }
  18.       },
  19.       get(index) {
  20.         if (isValidIndex(index)) {
  21.           return collection[index];
  22.         }
  23.       },
  24.       size: 0,
  25.     };
  26.     return collectionProcessor;
  27.  
  28.     function ascendingOrder(a, b) {
  29.       return a - b;
  30.     }
  31.  
  32.     function isValidIndex(index) {
  33.       return index >= 0 && index < collection.length;
  34.     }
  35.   }());
  36.   return list;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment