Search code examples
javascriptalgorithmfunctioncomputer-sciencetheory

How do I make a "composite key" (and what is this even called)?


I have two key strings, representing two objects of two different classes of objects. The keys are unique within their classes. I need to create a unique key representing the combination of these two keys. How do I do this?

I can't just concatenate them, because any character could be present in the base keys. I could maybe escape the concatenation delimiter before I concatenate? I could create a hash of the two keys, but this feels heavy.

Are there built in functions to help me do this? Is this "called something"? It seems like this would be a common (solved) problem.

(I'm looking for this specifically in Javascript, but I'm curious about higher level solutions or frameworks as well)


Solution

  • Simply concatenate the two strings, but prefix the first string with its length, and a separator. For example, if the input strings are "cat" and "doorbell", the output string would be "3:catdoorbell". On the other hand, if the inputs were "catdoor" and "bell", the output would be "7:catdoorbell".

    With this method, the outputs are unique, and the original keys are recoverable from the output string.