Implement a groupBy() Polyfill to Categorize Array Elements by a Key Function

Write a groupBy(array, keyFn) function (polyfill for the upcoming Array.prototype.groupBy() TC39 proposal) that partitions array elements into groups based on the string key returned by keyFn for each element. The output is an object (or Map) where each key maps to an array of matching elements. Handle edge cases like null/undefined keys, non-string key functions, and Map vs object output modes. This is the JS equivalent of SQL's GROUP BY.

Examples
Input: []
Output:
Hints

Implement a groupBy() Polyfill to Categorize Array Elements by a Key Function

Write a groupBy(array, keyFn) function (polyfill for the upcoming Array.prototype.groupBy() TC39 proposal) that partitions array elements into groups based on the string key returned by keyFn for each element. The output is an object (or Map) where each key maps to an array of matching elements. Handle edge cases like null/undefined keys, non-string key functions, and Map vs object output modes. This is the JS equivalent of SQL's GROUP BY.