jeudi 29 décembre 2016

How to get a consistent number representation of a string in Javascript

Background

I wish to seed a pseudo random number generator in JavaScript that will only accept numbers as arguments, the data I wish to use is currently a human readable string IE "How ya doing there Bob#42? Loving life in the clone vats?"

The Question

What is the simplest and most efficient way to turn that string into a number that is

A: Consistent, the same string always returns the same number.

B: Unique-ish, I would like to resist collisions between strings at least as much as is easily reasonable.

C: Simple, I don't want this to be a huge part of either my code base or resource footprint, it is NOT a high priority that it be terribly clever (no crypto here folks!)

Details

This is all in service to an attempt to pick a pseudo random item from a list of items to suggest to a user, and I want to have the suggestion remain the same for any number of times I run the suggestion algorithm, as long as they don't change the ID and NAME fields on their current screen. If there's a better answer for PRNG then feeding these strings in as the seed to a PRNG (that I already happen to have) I'm all ears.

My string may contain any number of any form of special characters allowed by ASCII. My string IS the result of a direct (unscrubbed) user input (exec feels bad here). I could dig around for the scrubbed version... but that feels like unneeded effort (system resource wise) right here.

My representation need not be bi-directional (it'll only seed a PRNG) and it need not be entirely unique (this just feeds a suggestion system, the user will make the final selection).




Aucun commentaire:

Enregistrer un commentaire