Skip to content

Commit

Permalink
Added smart cleanup pattern hook
Browse files Browse the repository at this point in the history
  • Loading branch information
silversonicaxel committed Aug 27, 2024
1 parent 2a509eb commit 85de09f
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/domains/scrobbleAlbum/partials/Tracklist.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { cleanupLastEndStringOccurrence } from 'utils/common';
import type { Album, DiscogsAlbum } from 'utils/types/album';
import type { Scrobble } from 'utils/types/scrobble';
import type { Track } from 'utils/types/track';
import { usePatternSmart } from 'hooks/usePatternSmart';

const DateTimePicker = lazyWithPreload(() => import('components/DateTimePicker'));

Expand Down Expand Up @@ -101,6 +102,11 @@ export default function Tracklist({ albumInfo, tracks }: { albumInfo: Album | nu
setUseCleanupPattern(event.target.value);
}, []);

const cleanupPatternSmart = usePatternSmart({
pattern: useCleanupPattern,
totalTrackNames: Array.from(tracks) as Scrobble[],
});

const scrobbleSelectedTracks = () => {
const userHasNotSelectedTracks = selectedTracks.size < 1;
const timestampCalculationSubstractsTime = !useCustomTimestamp;
Expand All @@ -119,7 +125,7 @@ export default function Tracklist({ albumInfo, tracks }: { albumInfo: Album | nu
.reduce((result, track) => {
const newTrack = {
...track,
title: useCleanupPattern !== '' ? cleanupLastEndStringOccurrence(track.title, useCleanupPattern) : track.title,
title: cleanupPatternSmart !== '' ? cleanupLastEndStringOccurrence(track.title, cleanupPatternSmart) : track.title,
album: albumInfo?.name || '',
albumArtist: albumInfo?.artist || '',
timestamp: rollingTimestamp,
Expand Down Expand Up @@ -258,7 +264,7 @@ export default function Tracklist({ albumInfo, tracks }: { albumInfo: Album | nu
noMenu
analyticsEventForScrobbles="Scrobble individual album song"
scrobbles={tracks || []}
scrobblesCleanupPattern={useCleanupPattern}
scrobblesCleanupPattern={cleanupPatternSmart}
onSelect={toggleSelectedTrack}
selected={selectedTracks}
>
Expand Down
37 changes: 37 additions & 0 deletions src/hooks/usePatternSmart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useMemo } from 'react';
import { keyOfLongestArray } from 'utils/common';
import type { Scrobble } from 'utils/types/scrobble';

export type UsePatternSmartParams = {
pattern?: string;
totalTrackNames: Scrobble[];
};

export type UsePatternSmartResult = string;

export type UsePatternSmartHook = (params: UsePatternSmartParams) => UsePatternSmartResult;

const USE_PATTERN_SMART_EXTRA_CHARS = ['-', '- ', '/', '/ '];

export const usePatternSmart: UsePatternSmartHook = ({ pattern, totalTrackNames }) => {
const allPatterns = useMemo<Record<string, Scrobble[]>>(() => {
const patterns: Record<string, Scrobble[]> = {};

USE_PATTERN_SMART_EXTRA_CHARS.forEach((extraChar: string) => {
totalTrackNames.forEach((track: Scrobble) => {
if (track.title.endsWith(extraChar + pattern)) {
patterns[extraChar] ??= [];
patterns[extraChar].push(track);
}
});
});

return patterns;
}, [pattern, totalTrackNames]);

if (!pattern) {
return '';
}

return Object.keys(allPatterns).length > 0 ? `${keyOfLongestArray(allPatterns)}${pattern}` : pattern;
};
46 changes: 46 additions & 0 deletions src/utils/common.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
sanitizeProvider,
replaceLastOccurrence,
cleanupLastEndStringOccurrence,
keyOfLongestArray,
sha256,
} from './common';

Expand Down Expand Up @@ -85,6 +86,51 @@ describe('`cleanupLastEndStringOccurrence` helper', () => {
});
});

describe('`keyOfLongestArray` helper', () => {
it('return first array as longest', () => {
const objectToAnalyze = {
longest: Array(5).fill(null),
second: Array(3).fill(null),
third: Array(3).fill(null),
};

expect(keyOfLongestArray(objectToAnalyze)).toBe('longest');
});

it('return last array as longest', () => {
const objectToAnalyze = {
first: Array(1).fill(null),
second: Array(3).fill(null),
longest: Array(5).fill(null),
};

expect(keyOfLongestArray(objectToAnalyze)).toBe('longest');
});

it('return a central array as longest', () => {
const objectToAnalyze = {
first: Array(1).fill(null),
second: Array(3).fill(null),
longest: Array(5).fill(null),
fourth: Array(3).fill(null),
};

expect(keyOfLongestArray(objectToAnalyze)).toBe('longest');
});

it('return the last array as one of the longest', () => {
const objectToAnalyze = {
first: Array(1).fill(null),
second: Array(3).fill(null),
third: Array(5).fill(null),
fourth: Array(3).fill(null),
longest: Array(5).fill(null),
};

expect(keyOfLongestArray(objectToAnalyze)).toBe('longest');
});
});

describe('`sha256` digest', () => {
it('returns the correct SHA-256 hash for a given string', () => {
const str = 'hello world';
Expand Down
15 changes: 15 additions & 0 deletions src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PROVIDER_DISCOGS, PROVIDER_NAME, Provider } from 'Constants';
import type { Scrobble } from './types/scrobble';

export function castArray(x: any): Array<any> {
return Array.isArray(x) ? x : [x];
Expand Down Expand Up @@ -36,6 +37,20 @@ export function cleanupLastEndStringOccurrence(fullString: string, pattern: stri
return fullString;
}

export function keyOfLongestArray(objectOfArrays: Record<string, Scrobble[]>): string {
let keyOfLongestArray: string = null;
let longestArrayLength = -1;

for (const [arrayKey, arrayItems] of Object.entries(objectOfArrays)) {
if (arrayItems.length >= longestArrayLength) {
longestArrayLength = arrayItems.length;
keyOfLongestArray = arrayKey;
}
}

return keyOfLongestArray;
}

export async function sha256(str: string) {
const msgUint8 = new TextEncoder().encode(str); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
Expand Down

0 comments on commit 85de09f

Please sign in to comment.