getAdapter

The getAdapter function provides a mechanism to retrieve or initialize a value associated with a specific key within an adaptable objet.

See also: newAdapter

Implementation
function getAdapter<T, A = unknown>(
  adapterKey: string,
  create: (adaptable: A) => T,
): [get: (adaptable: A) => T, remove: (adaptable: A) => void] {
  const get = (adaptable: A) => {
    const obj = adaptable as Record<string, T>;
    let value = obj[adapterKey];
    if (value === undefined) {
      value = obj[adapterKey] = create(adaptable);
    }
    return value;
  };
  const remove = (adaptable: A) => {
    const obj = adaptable as Record<string, T>;
    delete obj[adapterKey];
  };
  return [get, remove];
}
Implementation based on newAdapter

This function can also be implemented using the newAdapter method:

function getAdapter<T, A = unknown>(
  adapterKey: string,
  create: (adaptable: A) => T,
): [get: (adaptable: A) => T, remove: (adaptable: A) => void] {
  const [get, set] = newAdapter<T|undefined,A>(adapterKey);
  return [
    (adaptable: A) => get(adaptable) ?? set(adaptable, create(adaptable)) as T,
    (adaptable: A) => {
      set(adaptable, undefined);
    },
  ];
}

Method Signature

function getAdapter<T, A = unknown>(
  adapterKey: string,
  create: (adaptable: A) => T,
): [
  get: (adaptable: A) => T,
  remove: (adaptable: A) => void
];

Parameters:

Returns a tuple:

Behavior details:

Usage

getAdapter method examples:

const obj: Record<string, string> = {};
const getValue = getAdapter("myKey", () => "defaultValue");

console.log(getValue(obj)); // Outputs: "defaultValue"
obj["myKey"] = "customValue";
console.log(getValue(obj)); // Outputs: "customValue"