Search code examples
javascriptarrayshashtable

Understanding Algorithms in Javasciprt


I started to learn Algorithms in Javascript and I found a weird structure called hashtable on it that has not been possible to understand under the hood.

function findSumBetter(arr, weight) {
    var hashtable = {};

    for (var i = 0; i < arr.length; i++) {
        var currentElement = arr[i],
        difference = weight - currentElement;

        if (hashtable[currentElement] != undefined) {
            return [i, hashtable[currentElement]];
        } else {
            hashtable[difference] = i;
        }
    }

    return -1;
}

console.log(findSumBetter([1,2,3,4,5], 9)); // [4, 3]

Solution

  • Okay here is easy example: Let say you have JSON Object

    Assigning value 
     1 ) hashtable:{'Test1':90,'test2':45,'test3':60};
     // here Test1,Test2,Test3 are keyes
     2 ) hashtable['test1']=90
    Getting value:
    
     1) hashtable['Test1'] 
     2) hashtable.test1  
    Both will return the same result 90 in this example.
    

    --------In your case -------

     -- condition to check value is there 
      if (hashtable[currentElement] != undefined)
     -- you are assigning value to object
       hashtable[difference] = i;
     -- returning the value from object
       return [i, hashtable[currentElement]];