Hash String Into Number

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to hash a string into a whole number using the SDBM algorithm. We will use String.prototype.split() and Array.prototype.reduce() to create a hash of the input string, utilizing bit shifting. The purpose of this lab is to introduce you to the concept of hashing and how it can be used to generate unique identifiers for data.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28373{{"`Hash String Into Number`"}} javascript/data_types -.-> lab-28373{{"`Hash String Into Number`"}} javascript/arith_ops -.-> lab-28373{{"`Hash String Into Number`"}} javascript/comp_ops -.-> lab-28373{{"`Hash String Into Number`"}} javascript/higher_funcs -.-> lab-28373{{"`Hash String Into Number`"}} end

How to Hash a String into a Number Using JavaScript

To hash an input string into a whole number using JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the String.prototype.split() and Array.prototype.reduce() methods to create a hash of the input string, utilizing bit shifting.
  3. Here's the code for the sdbm function that implements the hashing algorithm:
const sdbm = (str) => {
  let arr = str.split("");
  return arr.reduce(
    (hashCode, currentVal) =>
      (hashCode =
        currentVal.charCodeAt(0) +
        (hashCode << 6) +
        (hashCode << 16) -
        hashCode),
    0
  );
};
  1. To test the function, call it with a string argument:
sdbm("name"); // -3521204949

This will return the hash value for the input string "name".

Summary

Congratulations! You have completed the Hash String Into Number lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like