From 327b16ac2e038892a1bc1fa4ecf619f0f69f77d0 Mon Sep 17 00:00:00 2001 From: npezza93 Date: Sat, 27 Jan 2018 21:30:24 -0500 Subject: [PATCH] Add repeat polyfill for repeating a string --- src/utils/Generic.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/utils/Generic.ts b/src/utils/Generic.ts index 4bc6c487f..9f9d2666f 100644 --- a/src/utils/Generic.ts +++ b/src/utils/Generic.ts @@ -11,3 +11,31 @@ export function contains(arr: any[], el: any): boolean { return arr.indexOf(el) >= 0; } + +/** + * Returns a string repeated a given number of times + * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat + * @param {Number} count The number of times to repeat the string + * @param {String} string The string that is to be repeated + */ +export function repeat(count: number, str: string): string { + if (count < 0) throw new RangeError('repeat count must be non-negative'); + if (count === Infinity) throw new RangeError('repeat count must be less than infinity'); + + count = Math.floor(count); + if (str.length === 0 || count === 0) return ''; + + // Ensuring count is a 31-bit integer allows us to heavily optimize the + // main part. But anyway, most current (August 2014) browsers can't handle + // strings 1 << 28 chars or longer, so: + if (str.length * count >= 1 << 28) { + throw new RangeError('repeat count must not overflow maximum string size'); + } + + let rpt = ''; + for (let i = 0; i < count; i++) { + rpt += str; + } + + return rpt; +}