From 1a6226270ff3ab812df3c4348b4fafe6cebb0200 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 13 Dec 2018 23:36:01 +0100 Subject: [PATCH] Fix setting aspect ratio in percentage (#2289) * Fix setting aspect ratio in percentage * Use endsWith * Fix invalid test --- src/common/util/parse-aspect-ratio.ts | 42 +++++++++++-------- .../common/util/parse_aspect_ratio_test.ts | 6 +-- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/src/common/util/parse-aspect-ratio.ts b/src/common/util/parse-aspect-ratio.ts index cd80d4b90d..8fb1dee0a2 100644 --- a/src/common/util/parse-aspect-ratio.ts +++ b/src/common/util/parse-aspect-ratio.ts @@ -1,24 +1,30 @@ -export default function parseAspectRatio(input) { - // Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 - // Ignore everything else - function parseOrThrow(num) { - const parsed = parseFloat(num); - if (isNaN(parsed)) { - throw new Error(`${num} is not a number`); - } - return parsed; +// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 +// Ignore everything else +const parseOrThrow = (num) => { + const parsed = parseFloat(num); + if (isNaN(parsed)) { + throw new Error(`${num} is not a number`); + } + return parsed; +}; + +export default function parseAspectRatio(input: string) { + if (!input) { + return null; } try { - if (input) { - const arr = input.replace(":", "x").split("x"); - if (arr.length === 0) { - return null; - } - - return arr.length === 1 - ? { w: parseOrThrow(arr[0]), h: 1 } - : { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) }; + if (input.endsWith("%")) { + return { w: 100, h: parseOrThrow(input.substr(0, input.length - 1)) }; } + + const arr = input.replace(":", "x").split("x"); + if (arr.length === 0) { + return null; + } + + return arr.length === 1 + ? { w: parseOrThrow(arr[0]), h: 1 } + : { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) }; } catch (err) { // Ignore the error } diff --git a/test-mocha/common/util/parse_aspect_ratio_test.ts b/test-mocha/common/util/parse_aspect_ratio_test.ts index 15b42a0cc1..758010aefa 100644 --- a/test-mocha/common/util/parse_aspect_ratio_test.ts +++ b/test-mocha/common/util/parse_aspect_ratio_test.ts @@ -31,9 +31,9 @@ describe("parseAspectRatio", () => { assert.deepEqual(r, ratio178); }); - it("Skips null states", () => { - const r = parseAspectRatio(null); - assert.equal(r, null); + it("Parses 23%", () => { + const r = parseAspectRatio("23%"); + assert.deepEqual(r, { w: 100, h: 23 }); }); it("Skips empty states", () => {