var hasher = require("./hash");

module.exports = function(size) {
  var hashtable = new Array(size = 1 << Math.ceil(Math.log(size) / Math.LN2)),
      hash = hasher(size);
  return {
    size: size,
    peek: function(key) {
      var matches = hashtable[hash(key)];

      if (matches) {
        var i = -1,
            n = matches.length,
            match;
        while (++i < n) {
          match = matches[i];
          if (equal(match.key, key)) {
            return match.values;
          }
        }
      }

      return null;
    },
    get: function(key) {
      var index = hash(key),
          matches = hashtable[index];

      if (matches) {
        var i = -1,
            n = matches.length,
            match;
        while (++i < n) {
          match = matches[i];
          if (equal(match.key, key)) {
            return match.values;
          }
        }
      } else {
        matches = hashtable[index] = [];
      }

      var values = [];
      matches.push({key: key, values: values});
      return values;
    }
  };
};

function equal(keyA, keyB) {
  return keyA[0] === keyB[0]
      && keyA[1] === keyB[1];
}
