Add tags module
This commit is contained in:
parent
e5c8f8c146
commit
335f7dc281
|
@ -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']]);
|
||||
});
|
17
src/tags.ts
17
src/tags.ts
|
@ -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 };
|
||||
|
|
Loading…
Reference in New Issue