All files / problems/binaryInventory index.ts

100% Statements 43/43
100% Branches 11/11
100% Functions 4/4
100% Lines 43/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 441x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 23x 23x 22x 22x 23x 42x 6x 6x 6x 42x 23x 16x 16x 22x 23x 4x 4x 25x 25x 4x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 1x 1x  
import { faker } from "@faker-js/faker";
import { binarySearch } from "../../binarySearch";
 
const binaryInventory = () => {
  const inventory: string[] = [];
 
  // add item to inventory
  // if item already exists, do not add
  // if item does not exist, add it
  // make sure item sorted alphabetically
  const add = (item: string) => {
    const alreadyExist = haveItem(item);
    if (alreadyExist) return;
 
    let insertIndex;
    for (let x = 0; x < inventory.length; x++) {
      if (item < inventory[x]) {
        insertIndex = x;
        break;
      }
    }
    if (insertIndex == undefined) {
      insertIndex = inventory.length;
    }
    inventory.splice(insertIndex, 0, item);
  };
 
  const haveItem = (item: string) => {
    return binarySearch(inventory, item) !== -1;
  };
 
  const getList = () => {
    return inventory;
  };
 
  return {
    add,
    getList,
    haveItem,
  };
};
 
export default binaryInventory;