Skip to content

Commit

Permalink
Change eval to regex
Browse files Browse the repository at this point in the history
Add test for regex

Co-authored-by: linusha <[email protected]>
  • Loading branch information
T4rikA and linusha committed Jun 10, 2021
1 parent 21222f5 commit 32b0429
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
14 changes: 12 additions & 2 deletions editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -1436,7 +1436,7 @@ class MenuBar extends QinoqMorph {
}
}

class Settings extends QinoqMorph {
export class Settings extends QinoqMorph {
static get properties () {
return {
name: {
Expand Down Expand Up @@ -1549,7 +1549,8 @@ class Settings extends QinoqMorph {

inputLineUpdate (input) {
try {
const newRatio = eval(input);
const newRatio = Settings.matchNumberOrFraction(input);
if (!newRatio) throw new Error('The input was not a number!');
this.interactive.fixedAspectRatio = newRatio;
this.editor.onInteractiveZoomed();
success('Ratio updated!');
Expand All @@ -1558,6 +1559,15 @@ class Settings extends QinoqMorph {
}
}

static matchNumberOrFraction (inputString) {
// eslint-disable-next-line no-useless-escape
const match = inputString.match(RegExp('^(\\d+)((\\.\\d+)|(\\/\\d+))?$', 'i'));
if (!match) return null;
if (!match[2]) return Number(match[1]);
if (match[2].includes('.')) return Number(match[1].concat(match[3]));
if (match[2].includes('/')) return Number(match[1]) / Number(match[4].substring(1));
}

dropDownSelectorUpdate (input) {
if (input == 'Custom') {
this.ui.inputLine.visible = true;
Expand Down
23 changes: 23 additions & 0 deletions tests/settings-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* global it, describe */
import { expect } from 'mocha-es6';
import { Settings } from '../editor.js';

describe('Settings', () => {
it('parses fractions and numbers in correct formats', () => {
expect(Settings.matchNumberOrFraction('3')).to.be.equal(3);
expect(Settings.matchNumberOrFraction('4/3')).to.be.equal(4 / 3);
expect(Settings.matchNumberOrFraction('3.5')).to.be.equal(3.5);
expect(Settings.matchNumberOrFraction('3123.123')).to.be.equal(3123.123);
expect(Settings.matchNumberOrFraction('3123/123')).to.be.equal(3123 / 123);
});

it('parses fractions and numbers in incorrect formats', () => {
expect(Settings.matchNumberOrFraction('123/456.789')).to.be.null;
expect(Settings.matchNumberOrFraction('123.456/789')).to.be.null;
expect(Settings.matchNumberOrFraction('3.')).to.be.null;
expect(Settings.matchNumberOrFraction('3/')).to.be.null;
expect(Settings.matchNumberOrFraction('[3/4]')).to.be.null;
expect(Settings.matchNumberOrFraction('[3/')).to.be.null;
expect(Settings.matchNumberOrFraction('{3/}')).to.be.null;
});
});

0 comments on commit 32b0429

Please sign in to comment.