Home > Net >  How to create fast and small hash on Javascript/Typescript (in the browser) and convert it to a numb
How to create fast and small hash on Javascript/Typescript (in the browser) and convert it to a numb

Time:11-03

I need the following function and it needs to be performant. I really don't know how to go about this.

function(value: string): number { ... }

The returned number needs to be between 0 and 15 and always return the same number for given strings. Duplicates are obviously allowed!

I did something similar on Node a while back but I think this would not be performant enough for my use case:

function(value: string): number {
  const hash = crypto.createHash("sha256");
  const hexValue: string = hash.update(value).digest("hex");
  const shortenedHexValue = hexValue.substring(0, 2);
  const decimalValue = parseInt(shortenedHexValue, 16);
  return decimalValue / 2.55;
}

This function returned values > 0 to ~100 for given strings.

CodePudding user response:

According to the comments under your post, you need something that looks "random", so you can't do:

function hash15(value: string): number {
    return 0;
}

event if it corresponds to all you specifications.

For the random part, we can use ASCII code of each char of your string, as @Alois Christen suggested:

function hash15(value: string): number {
    let res = 0;
    for (let i = 0; i < value.length; i  ) {
        res  = value.charCodeAt(i);
    }
    return res % 16;
}

If you need it to be faster, you can skip characters:

function hash15(value: string): number {
    let res = 0;
    for (let i = 0; i < value.length / 2; i =2) {
        res  = value.charCodeAt(i);
    }
    return res % 16;
}
  • Related