Skip to content

Instantly share code, notes, and snippets.

@laat
Created November 19, 2019 11:43
Show Gist options
  • Save laat/bb7014ac679e8ec37d8718089a883674 to your computer and use it in GitHub Desktop.
Save laat/bb7014ac679e8ec37d8718089a883674 to your computer and use it in GitHub Desktop.
simple ponyfills
/**
* Element.closest ponyfill
*/
export function elementClosest(element: Element, selector: string): Element | null
export const elementClosest = (() => {
const proto = typeof window === "undefined" ? {} : window.Element.prototype;
const match =
proto.matches || proto.msMatchesSelector || proto.webkitMatchesSelector;
return proto.closest
? (el, css) => el.closest(css)
: (el, css) => {
// IE jumps to shadow SVG DOM on clicking an SVG defined by <use>.
// If so, jump back to <use> element and traverse real DOM
if (el.correspondingUseElement) el = el.correspondingUseElement;
for (; el; el = el.parentElement) if (match.call(el, css)) return el;
return null;
};
})();
/**
* Object.entries ponyfill
*/
export function objectEntries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][]
export function objectEntries(o: {}): [string, any][];
export const objectEntries = Object.entries || ((obj) => {
const ownProps = Object.keys(obj);
let i = ownProps.length;
const resArray = new Array(i); // preallocate the Array
while (i--) resArray[i] = [ownProps[i], obj[ownProps[i]]];
return resArray;
});
/**
* Object.fromEntries ponyfill
*/
export function ObjectFromEntries<T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k in PropertyKey]: T };
export function ObjectFromEntries(entries: Iterable<readonly any[]>): any;
export const objectFromEntries =
Object.fromEntries ||
(iterable =>
[...iterable].reduce((obj, [key, val]) => {
obj[key] = val;
return obj;
}, {}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment