Uneventful
    Preparing search index...

    Function method

    • Experimental

      Create an extension method: a function that invokes a memoized closure for a given target object or function.

      This function is almost identical to ext(), except that instead of an accessor function, this returns a function that will call the extension (method closure) corresponding to the target, passing along any extra arguments.

      This is useful when you want to create an extension type that only has one public method, and you'd rather not create a whole class for it: just set up its state as variables in your factory function and return a closure. Then, you can simply call myMethod(target, ...args), which will look up the (possibly cached) closure for target and call it with (...args). (You could do the same thing with an ext() accessor, but then the API would be myMethod(target)(...args).)

      Type Parameters

      • Target extends object

        The type of target object that will be extended. Both the passed-in factory function and the returned accessor function will take a parameter of this type, which must be an object or function type. (So it's suitable for weak referencing.)

      • Method extends PlainFunction

        The type of the closure that will be cached. The passed-in factory function must return a value of this type, and the resulting wrapper function will be of the same type but with an added initial target parameter. (Note: if this type has more than one call signature, only the last overload will be used in the resulting method signature, due to TypeScript compiler limitations.)

      Parameters

      • factory: (tgt: Target, map: WeakMap<Target, Method>) => Method

        Function called with a target object or function and a weakmap to create a method closure for that target. The result is cached in the weakmap so the factory is called at most once per target (unless you alter the weakmap contents directly).

      • map: WeakMap<Target, Method> = ...

        Optional: the weakmap to use to store the method closures. This allows you to manipulate the map contents (e.g. remove items or clear it) from outside the factory function. If no map is provided, one is created automatically, but then it's only accessible via the factory function's second parameter.

      Returns (tgt: Target, ...args: Parameters<Method>) => ReturnType<Method>

      A wrapper function that always invokes the same closure for a given target (assuming you don't alter the WeakMap), calling the factory function if a method closure doesn't exist yet for that target. When called, the wrapper function returns the result of calling the closure with the same arguments (minus an initial target argument).