1

For example: I have key1 = "abc" and key2="xyz".

I want to write a function that will return the same value regardless of the order of parameters.

So foo(key1, key2) and foo(key2, key1) should both the same value ex. "123".

I am thinking of some kind of hashing, but not quite sure what's the best approach to make this as efficient as possible.

Would appreciate any ideas, I am implementing it in javascript/node.js

zsayn
  • 217
  • 1
  • 3
  • 8
  • 1
    Doesn't sound like a great idea TBH. You're making it less secure by ignoring order. Part of the point of the hash, is that you order quite precisely to produce a single result. This will then mean that you wish two unique inputs (A,B & B,A) to map onto a single result. You will know the order of input to a hash. If you like, you can order them alphabetically based on their values or something, but you should know the technique that you are employing for the ordering when you do the hash such that it results in a one to one mapping. What's your use case for this requirement? – ManoDestra Apr 25 '16 at 19:50
  • I know, it's a weird req't, but that's exactly what they need A,B & B,A mapping to the same object. Yes, sorting works, so simple :) – zsayn Apr 26 '16 at 00:33
  • Yes, I see what you mean now. Just sort the required fields in a prescribed order, either ascending or descending. And add your salt, private key, timestamp, etc. Then hash it. Simple :) – ManoDestra Apr 26 '16 at 13:12

1 Answers1

3

If the inputs are strings, then you can just sort the strings, combine them and then hash the combined string. The sorting will get you a consistent hash value, no matter the order of the keys passed in.

function foo(key1, key2) {
    var sortedKeys = Array.prototype.slice.call(arguments).sort();
    return makeHash(sortedKeys.join("-"));
}

You supply the makeHash() function as desired. Here are some possibilities for the hash function.

Note: This implementation takes any number of arguments. If you want only use the first two arguments or want to throw an exception if there are more or less than two arguments, either of those behaviors can be easily added.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Essentially what I was trying to describe in my comment above, concisely done. Good job :) – ManoDestra Apr 25 '16 at 20:23
  • Thank you jfriend00, I don't know why I didn't think about just sorting the inputs, of course that makes perfect sense. – zsayn Apr 26 '16 at 00:32