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:
adapterKey
(string
) – the key whose value needs to be retrieved or initialized.create(adaptable: A) => T
– a function that generates a new adapter if it is not found in the adaptable object.
Returns a tuple:
get(adaptable: A) => T
– retrieves the value associated with the key in the given adaptable object.remove(adaptable: A) => void
– removes the adapter from the adaptable object.
Behavior details:
- If the key already exists in the adaptable object its value is returned.
- If the key is not found, the
create
function is called to initialize the value.
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"