DerivcoIpswich / dsharp

A fork of the Script# project.
http://www.derivco.co.uk
Other
20 stars 13 forks source link

Implement GetHashCode for every object #248

Open isc30 opened 4 years ago

isc30 commented 4 years ago

Possible default implementation:

JS:

(function() {
  var __gRefID = 0;
  window.getHashCode = function(ref)
  {
      if (ref == null) { throw Error("Unable to calculate HashCode on a null reference"); }

      // already cached reference id
      if (ref.hasOwnProperty("__refID")) { return ref["__refID"]; }

      // numbers are already hashcodes
      if (typeof ref === "number") { return ref; }

      // strings are immutable, so we need to calculate this every time
      if (typeof ref === "string")
      {
          var hash = 0, i, chr;
          for (i = 0; i < ref.length; i++) {
            chr = ref.charCodeAt(i);
            hash = ((hash << 5) - hash) + chr;
            hash |= 0;
          }
          return hash;
      }

      // virtual call
      if (typeof ref.getHashCode === "function") { return ref.getHashCode(); }

      // generate and return a new reference id
      return (ref["__refID"] = "ref" + __gRefID++);
  }
})();

Object.cs

public class Object
{
    // ...
    [ScriptAlias("getHashCode")]
    public virtual int GetHashCode();
}
isc30 commented 4 years ago

For our Dictionary, we can make it so Adding/Getting/Removing calls getHashCode instead of toString to optimize our own stuff