orderUniqueFirst.ts

import { getMapWithValueArray } from '../../utility/lib/map';

/**
 * Create a list where one item from each set is picked first,
 * and then it repeats the same until there are no items left.
 * @param map Map of comedian id's with their videos as list as value
 * @returns Videos ordered by picking recursively one video of each comedian first
 */
function firstItemsFirst(map) {
  let list = [];
  addItems(map, list);
  return list;
}

function addItems(map, list) {
  if (map.size === 0) {
    return list;
  } else {
    addFirstItems(map, list);
    addItems(map, list);
  }
}

// TODO add all if last item of the map
function addFirstItems(map, list) {
  for (const key of map.keys()) {
    const items = map.get(key);
    if (items.length === 0) throw 'Empty array was found';

    const item = items[0];
    list.push(item);

    if (items.length === 1) {
      map.delete(key);
    } else {
      const slicedList = items.slice(1);
      map.set(key, slicedList);
    }
  }
}

function getComedianVideosMap(videos) {
  return getMapWithValueArray(videos, 'comedianId');
}

export { firstItemsFirst, getComedianVideosMap };