All files / Rindu/utils findDuplicateSongs.ts

96.29% Statements 26/27
100% Branches 15/15
100% Functions 3/3
100% Lines 26/26

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67    10x       8x   8x   8x   22x             3x     19x   19x 19x 4x   15x   9x 15x 14x     1x     9x 4x         19x 8x     19x 11x 11x   11x         19x         8x     44x  
import { ITrack } from "types/spotify";
 
export function findDuplicateSongs(allTracks: ITrack[]): {
  index: number;
  id: string | null;
}[] {
  const seenByIds: Record<string, boolean> = {};
 
  const seenByNameAndArtist: Record<string, number[]> = {};
 
  const duplicateSongs = allTracks.reduce(
    (duplicates: { index: number; id: string }[], track, index) => {
      if (
        !track ||
        !track.id ||
        !track.name ||
        !Array.isArray(track.artists) ||
        !track.artists[0].name
      ) {
        return duplicates;
      }
 
      let isDuplicate = false;
      const seenNameAndArtistKey =
        `${track.name}:${track.artists[0].name}`.toLowerCase();
      if (track.id in seenByIds) {
        isDuplicate = true;
      } else {
        if (seenNameAndArtistKey in seenByNameAndArtist) {
          const similarDuration =
            seenByNameAndArtist[seenNameAndArtistKey].filter((duration) => {
              if (track.duration_ms) {
                return Math.abs(duration - track.duration_ms) < 2000;
              }
 
              return false;
            }).length !== 0;
 
          if (similarDuration) {
            isDuplicate = true;
          }
        }
      }
 
      if (isDuplicate) {
        duplicates.push({ index, id: track.id });
      }
 
      if (!isDuplicate) {
        seenByIds[track.id] = true;
        seenByNameAndArtist[seenNameAndArtistKey] =
          seenByNameAndArtist[seenNameAndArtistKey] || [];
        seenByNameAndArtist[seenNameAndArtistKey].push(
          track.duration_ms as number
        );
      }
 
      return duplicates;
    },
    []
  );
 
  return duplicateSongs;
}
 
export default findDuplicateSongs;