Implement Polyfills for bind, call, apply, and compose

viaLeetCode

Requirements: Implement your own polyfills for Function.prototype.bind, Function.prototype.call, Function.prototype.apply, and a function-composition utility compose, demonstrating understanding of their internal working.

Design/Approach:

  • call/apply: temporarily attach the function as a property on the given this context (using a unique/Symbol key to avoid collisions), invoke it with the arguments (spread individually for call, as an array for apply), capture the result, then delete the temporary property and return the result.
  • bind: return a new function that, when later invoked, calls the original function with the bound this and the concatenation of the originally-bound arguments and any newly-supplied arguments; should also work correctly when the bound function is used as a constructor with new.
  • compose: given a list of functions, return a new function that threads a value through them (e.g. compose(f, g, h)(x) === f(g(h(x)))), passing the output of each function as the input to the next.
Add a follow-up question they asked
Write the compose() Polyfill After Being Explained It
asked …
LeaderboardSalary
Language
Account