diff --git a/src/tags.test.ts b/src/tags.test.ts new file mode 100644 index 0000000..9c7e938 --- /dev/null +++ b/src/tags.test.ts @@ -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']]); +}); diff --git a/src/tags.ts b/src/tags.ts index 98efc7d..a55560c 100644 --- a/src/tags.ts +++ b/src/tags.ts @@ -11,4 +11,19 @@ function getTagSet(tags: string[][], tagName: string): Set { 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 };