Skip to content

Instantly share code, notes, and snippets.

@lubieowoce
Created February 14, 2024 20:32
Show Gist options
  • Save lubieowoce/0cf824c773951b30f1df7c6a4622c636 to your computer and use it in GitHub Desktop.
Save lubieowoce/0cf824c773951b30f1df7c6a4622c636 to your computer and use it in GitHub Desktop.
We have Record/Tuple at home
/// <reference types="react/canary" />
import React, { cache } from "react";
type Options = { passthrough?: boolean };
const OPTIONS_DEFAULT: Options = { passthrough: false };
type RecordOrTupleArg = Record<string, any> | any[]
export function cacheValue<TObj extends RecordOrTupleArg>(
v: RecordOrTupleArg,
opts = OPTIONS_DEFAULT
): TObj {
const currentTag = getCurrentCacheTag();
const seenObjects = new Set();
function cacheValueImpl(v: unknown) {
if (!(v && typeof v === "object")) {
return v;
}
const existingTag = v[CacheTag];
if (existingTag && existingTag === currentTag) {
// if this is tagged as a record/tuple AND it's from the current request,
// we can return it unchanged.
return v;
} else {
// otherwise, it's a leftover from some previous request,
// and that cache is gone,
// so we have to re-intern it into the current cache.
}
if (!isRecordOrTupleCompatible(v)) {
if (opts.passthrough) {
return v;
}
throw new Error(`Got a non-plain object value: ${v + ""}`);
}
// intern the value.
if (seenObjects.has(v)) {
throw new Error("cacheValue cannot memoize circular objects");
}
seenObjects.add(v);
if (Array.isArray(v)) {
return cacheTuple(v);
} else {
return cacheRecord(v);
}
}
function cacheTuple(arr: unknown[]) {
const items = arr.map((v) => cacheValueImpl(v));
const cell = getCellFromItems_Tuple.apply(null, items);
let value = cell.value;
if (!value) {
value = createFreshTuple(arr);
cell.value = value;
}
return value;
}
function cacheRecord(obj: Record<string, unknown>) {
const items = concatAll(
Object.entries(obj)
.map(
([k, v]) => [k, cacheValueImpl(v)] as [key: string, value: typeof v]
)
.sort(compareEntriesByKey)
);
const cell = getCellFromItems_Record.apply(null, items);
let value = cell.value;
if (!value) {
value = createFreshRecord(obj);
cell.value = value;
}
return value;
}
return cacheValueImpl(v) as TObj;
}
class Cell<T> {
value: T | null
constructor(value: T | null) {
this.value = value;
}
}
const getCellFromItems_Record = cache((..._items: unknown[]) => new Cell(null));
const getCellFromItems_Tuple = cache((..._items: unknown[]) => new Cell(null));
const getCurrentCacheTag = cache(() => ({}));
const CacheTag = Symbol("cacheValue.CacheTag");
function createFreshRecord(obj: Record<string, unknown>) {
const value = { ...obj };
tagCachedValue(value);
return Object.freeze(value);
}
function createFreshTuple(obj: unknown[]) {
const value = [...obj];
tagCachedValue(value);
return Object.freeze(value);
}
function tagCachedValue(value: Record<string, unknown> | unknown[]) {
Object.defineProperty(value, CacheTag, {
value: getCurrentCacheTag(),
enumerable: false,
});
}
function concatAll<T>(arrays: T[][]): T[] {
return Array.prototype.concat.apply(Array.prototype, arrays);
}
type ObjectEntry<T> = [key: string, value: T];
function compareEntriesByKey(
[k1]: ObjectEntry<unknown>,
[k2]: ObjectEntry<unknown>
) {
return k1 < k2 ? -1 : k1 > k2 ? 1 : 0;
}
function isRecordOrTupleCompatible(
value: unknown
): value is unknown[] | Record<string, unknown> {
return Array.isArray(value) || isPlainObject(value);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
// Source: https://github.com/sindresorhus/is-plain-obj
// MIT License
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
if (typeof value !== "object" || value === null) {
return false;
}
const prototype = Object.getPrototypeOf(value);
return (
(prototype === null ||
prototype === Object.prototype ||
Object.getPrototypeOf(prototype) === null) &&
!(Symbol.toStringTag in value) &&
!(Symbol.iterator in value)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment