In the realm of JavaScript, the need arises to transform strings into a compact form of representation known as a hash. Unlike server-side languages, JavaScript presents a unique challenge for this task.
Fortunately, JavaScript provides a solution through the use of the hashCode() method. This method, when applied to a string, generates a unique hash value that serves as a fingerprint for the string.
Implementation:
String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; };
Usage:
const str = 'revenue'; console.log(str, str.hashCode());
Output:
revenue 557163167
The above is the detailed content of How Can I Efficiently Hash Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!