callable-instance.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. export const CallableInstance =
  2. /**
  3. * @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}
  4. */
  5. (
  6. /** @type {unknown} */
  7. (
  8. /**
  9. * @this {Function}
  10. * @param {string | symbol} property
  11. * @returns {(...parameters: Array<unknown>) => unknown}
  12. */
  13. function (property) {
  14. const self = this
  15. const constr = self.constructor
  16. const proto = /** @type {Record<string | symbol, Function>} */ (
  17. // Prototypes do exist.
  18. // type-coverage:ignore-next-line
  19. constr.prototype
  20. )
  21. const value = proto[property]
  22. /** @type {(...parameters: Array<unknown>) => unknown} */
  23. const apply = function () {
  24. return value.apply(apply, arguments)
  25. }
  26. Object.setPrototypeOf(apply, proto)
  27. // Not needed for us in `unified`: we only call this on the `copy`
  28. // function,
  29. // and we don't need to add its fields (`length`, `name`)
  30. // over.
  31. // See also: GH-246.
  32. // const names = Object.getOwnPropertyNames(value)
  33. //
  34. // for (const p of names) {
  35. // const descriptor = Object.getOwnPropertyDescriptor(value, p)
  36. // if (descriptor) Object.defineProperty(apply, p, descriptor)
  37. // }
  38. return apply
  39. }
  40. )
  41. )