Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 23 additions & 17 deletions src/common/util/parse-aspect-ratio.ts
Original file line number Diff line number Diff line change
@@ -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;
}
if (input.endsWith("%")) {
return { w: 100, h: parseOrThrow(input.substr(0, input.length - 1)) };
}

return arr.length === 1
? { w: parseOrThrow(arr[0]), h: 1 }
: { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[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
}
Expand Down
6 changes: 3 additions & 3 deletions test-mocha/common/util/parse_aspect_ratio_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down