Define your own hash () method for use with ES6 cards

To illustrate the problem, consider the following simple object

function Key( val ) {
  this._val = val;
}

Now I create an instance of ES6 Mapand load one entry into it, like this

var map = new Map(),
    key1 = new Key( 'key' );

map.set( key1, 'some value' );

console.log( 'key1: ', map.has( key1 ) );
// key1:  true

So far so good. However, the problem arises if I create an almost identical object key2like this

var key2 = new Key( 'key' );

So basically both keys are identical, but obviously key2not part of the map

console.log( 'key2: ', map.has( key2 ) );
// key2:  false

JavaScript uses object references as the key here, so two separate objects will not point to the same value.

Now I would like to add something like a method hash()to the key prototypeso that both objects point to the same key. Is something like this possible?


, , factory Key . , , . , .

+5
2

?

, ES6. , , , .

, ( - , ) . , Key, . , , .

+5

CanonMap big-m, .

, :

const { CanonMap } = "big-m";

const myMap = new CanonMap();
myMap.set(
  ["Farooq", "867-5309"],
  36.59
);

myMap.get(
  ["Farooq", "867-5309"]
) === 36.59;

myMap.set(
  {name: "Farooq", number: "867-5309"},
  36.59
);

myMap.get(
  {number: "867-5309", name: "Farooq"} // Insensitive to key ordering
) === 36.59;

myMap.set(new Date(2012, 6, 5), "Tuesday");
myMap.get(new Date(2012, 6, 5)) === "Tuesday";

canonizer, , :

import {naiveCanonize, jsonCanonize, JsonCanonMap, CanonMap} from "big-m";

// Same as default canonizer, but with greater recursion depth (default is 2)
new CanonMap([], 6);

// Canonize by ID with fallback to naive
const customCanonMap = new CanonMap([
  [{id: "TEST1", x: 7}, 77],
  [{ x: 7 }, 88]
], lookup => lookup.id || naiveCanonize(lookup));

customCanonMap.get({id: "TEST1", x: 8}) === 77; // Ignores other values, uses ID
customCanonMap.get({x: 8}) === undefined; // Uses all fields, so lookup fails

// Default canonizer with JSON.stringify
new CanonMap([], jsonCanonize);
// equivalent to
new CanonMap([], lookup => JSON.stringify(lookup));
// also equivalent to
new JsonCanonMap(); 

, CanonMap, - , , - :

const selfHashingCanonMap = new CanonMap([], lookup => {
  if ("hash" in lookup) {
    return lookup.hash();
  } else {
    return naiveCanonize(lookup);
  }
});
0

Source: https://habr.com/ru/post/1599259/


All Articles