swr-devtools
Version:
A React component for SWR DevTools
67 lines • 2.45 kB
JavaScript
// Taken from https://github.com/vercel/swr/blob/9ea4a45c1620b31fb3a5a09771e0809638f47974/_internal/utils/hash.ts
var OBJECT = Object;
var isUndefined = function (v) { return typeof v === "undefined"; };
// use WeakMap to store the object->key mapping
// so the objects can be garbage collected.
// WeakMap uses a hashtable under the hood, so the lookup
// complexity is almost O(1).
var table = new WeakMap();
// counter of the key
var counter = 0;
// A stable hash implementation that supports:
// - Fast and ensures unique hash properties
// - Handles unserializable values
// - Handles object key ordering
// - Generates short results
//
// This is not a serialization function, and the result is not guaranteed to be
// parsable.
export var stableHash = function (arg) {
var type = typeof arg;
var constructor = arg && arg.constructor;
var isDate = constructor == Date;
var result;
var index;
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {
// Object/function, not null/date/regexp. Use WeakMap to store the id first.
// If it's already hashed, directly return the result.
result = table.get(arg);
if (result)
return result;
// Store the hash first for circular reference detection before entering the
// recursive `stableHash` calls.
// For other objects like set and map, we use this id directly as the hash.
result = ++counter + "~";
table.set(arg, result);
if (constructor == Array) {
// Array.
result = "@";
for (index = 0; index < arg.length; index++) {
result += stableHash(arg[index]) + ",";
}
table.set(arg, result);
}
if (constructor == OBJECT) {
// Object, sort keys.
result = "#";
var keys = OBJECT.keys(arg).sort();
while (!isUndefined((index = keys.pop()))) {
if (!isUndefined(arg[index])) {
result += index + ":" + stableHash(arg[index]) + ",";
}
}
table.set(arg, result);
}
}
else {
result = isDate
? arg.toJSON()
: type == "symbol"
? arg.toString()
: type == "string"
? JSON.stringify(arg)
: "" + arg;
}
return result;
};
//# sourceMappingURL=hash.js.map