Add tags module

This commit is contained in:
Alex Gleason 2023-12-31 14:05:04 -06:00
parent e5c8f8c146
commit 335f7dc281
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 41 additions and 1 deletions

25
src/tags.test.ts Normal file
View File

@ -0,0 +1,25 @@
import { assertEquals } from '@/deps-test.ts';
import { deleteTag, getTagSet, setTag } from './tags.ts';
Deno.test('getTagSet', () => {
assertEquals(getTagSet([], 'p'), new Set());
assertEquals(getTagSet([['p', '123']], 'p'), new Set(['123']));
assertEquals(getTagSet([['p', '123'], ['p', '456']], 'p'), new Set(['123', '456']));
assertEquals(getTagSet([['p', '123'], ['p', '456'], ['q', '789']], 'p'), new Set(['123', '456']));
});
Deno.test('setTag', () => {
assertEquals(setTag([], ['p', '123']), [['p', '123']]);
assertEquals(setTag([['p', '123']], ['p', '123']), [['p', '123']]);
assertEquals(setTag([['p', '123'], ['p', '456']], ['p', '123']), [['p', '123'], ['p', '456']]);
assertEquals(setTag([['p', '123'], ['p', '456']], ['p', '789']), [['p', '123'], ['p', '456'], ['p', '789']]);
});
Deno.test('deleteTag', () => {
assertEquals(deleteTag([], ['p', '123']), []);
assertEquals(deleteTag([['p', '123']], ['p', '123']), []);
assertEquals(deleteTag([['p', '123']], ['p', '456']), [['p', '123']]);
assertEquals(deleteTag([['p', '123'], ['p', '123']], ['p', '123']), []);
assertEquals(deleteTag([['p', '123'], ['p', '456']], ['p', '456']), [['p', '123']]);
});

View File

@ -11,4 +11,19 @@ function getTagSet(tags: string[][], tagName: string): Set<string> {
return set;
}
export { getTagSet };
/** Delete all occurences of the tag by its name/value pair. */
function deleteTag(tags: readonly string[][], tag: string[]): string[][] {
return tags.filter(([name, value]) => !(name === tag[0] && value === tag[1]));
}
/** Add a tag to the list, replacing the name/value pair if it already exists. */
function setTag(tags: readonly string[][], tag: string[]): string[][] {
const tagIndex = tags.findIndex(([name, value]) => name === tag[0] && value === tag[1]);
if (tagIndex === -1) {
return [...tags, tag];
} else {
return [...tags.slice(0, tagIndex), tag, ...tags.slice(tagIndex + 1)];
}
}
export { deleteTag, getTagSet, setTag };