From 0cbac8bb44563b4eaadf6eea288596467d9d7d6c Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Wed, 1 Sep 2021 16:23:41 +0200 Subject: [PATCH] Polyfill `Array.flat` (#9917) --- src/entrypoints/core.ts | 1 + src/resources/array.flat.polyfill.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/resources/array.flat.polyfill.ts diff --git a/src/entrypoints/core.ts b/src/entrypoints/core.ts index 964c2ca99c..3ba33d23b7 100644 --- a/src/entrypoints/core.ts +++ b/src/entrypoints/core.ts @@ -23,6 +23,7 @@ import { subscribePanels } from "../data/ws-panels"; import { subscribeThemes } from "../data/ws-themes"; import { subscribeUser } from "../data/ws-user"; import type { ExternalAuth } from "../external_app/external_auth"; +import "../resources/array.flat.polyfill"; import "../resources/safari-14-attachshadow-patch"; import { HomeAssistant } from "../types"; import { MAIN_WINDOW_NAME } from "../data/main_window"; diff --git a/src/resources/array.flat.polyfill.ts b/src/resources/array.flat.polyfill.ts new file mode 100644 index 0000000000..ad36844222 --- /dev/null +++ b/src/resources/array.flat.polyfill.ts @@ -0,0 +1,26 @@ +/* eslint-disable no-extend-native */ +// @ts-expect-error +if (!Array.prototype.flat) { + Object.defineProperty(Array.prototype, "flat", { + configurable: true, + writable: true, + value: function (...args) { + const depth = typeof args[0] === "undefined" ? 1 : Number(args[0]) || 0; + const result = []; + const forEach = result.forEach; + + const flatDeep = (arr: Array, dpth: number) => { + forEach.call(arr, (val) => { + if (dpth > 0 && Array.isArray(val)) { + flatDeep(val, dpth - 1); + } else { + result.push(val); + } + }); + }; + + flatDeep(this, depth); + return result; + }, + }); +}