diff --git a/src/types/TupleKey.ts b/src/types/TupleKey.ts new file mode 100644 index 0000000..08dcfb4 --- /dev/null +++ b/src/types/TupleKey.ts @@ -0,0 +1,19 @@ +const separator = "|"; + +export class TupleKey { + public readonly tuple: T; + private readonly strKey: string; + + constructor(...tuple: T) { + this.tuple = tuple; + this.strKey = tuple.join(separator); + } + + toString(): string { + return this.strKey; + } + + valueOf(): string { + return this.strKey; + } +} diff --git a/test/types/TupleKeyTests.test.ts b/test/types/TupleKeyTests.test.ts new file mode 100644 index 0000000..ac260dd --- /dev/null +++ b/test/types/TupleKeyTests.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "@jest/globals"; +import { TupleKey } from "../../src/types/TupleKey"; + +describe("TupleKey", () => { + it("stores a value copy of the original tuple", () => { + const tuple: [string, string] = ["150", "539"]; + const tupleKey = new TupleKey(...tuple); + + expect(tupleKey.tuple).toEqual(tuple); + }); + + it("returns a string representation of itself", () => { + const tuple: [string, string] = ["150", "539"]; + const tupleKey = new TupleKey(...tuple); + + expect(`${tupleKey}`).toEqual("150|539"); + }); + + it("supports usage as key in object", () => { + const tupleKey1 = new TupleKey("1", "2"); + const tupleKey2 = new TupleKey("3", "4"); + + const sampleObject = { + [tupleKey1.toString()]: "value1", + [tupleKey2.toString()]: "value2", + }; + + expect(sampleObject[tupleKey1.toString()]).toEqual("value1"); + expect(sampleObject[(new TupleKey("1", "2")).toString()]).toEqual("value1"); + }); +}); \ No newline at end of file