X-Git-Url: https://git.sommitrealweird.co.uk/cssbattle.git/blobdiff_plain/b3802de6e0d356f8f8ac42e420c905d12e131638..8b446ce74ff54596f0bf4403c9fb11501780a1ed:/unit_replacement.js?ds=sidebyside diff --git a/unit_replacement.js b/unit_replacement.js new file mode 100644 index 0000000..2f83635 --- /dev/null +++ b/unit_replacement.js @@ -0,0 +1,51 @@ +// 1ch -> 8px +// 1pc -> 12pt -> 1/6in -> 16px +// 1vw -> 4px +// 1vh -> 3px +// 1in -> 96px +// 1ex -> 7.16px (useful, right?!) +// 1em -> 16px - we'll just use pc for this instead +// 1q -> 100/106 px <-- this is a bad bad number, so, if we've already got q, we probably won't do anything with 'em' + +pixel_lengths = { + "ch": 8, + "pc": 16, + "vw":4, + "vh":3, + "in": 96, + "ex":7.16, + "em":16, + "px":1 +}; + +function getShortestUnit(length,unit) { + cur_string = `${length}${unit}`; + pixel_length = 0; + if (pixel_lengths.hasOwnProperty(unit)) { + pixel_length = length * pixel_lengths[unit]; + } + else { + return cur_string; + } + for (unit in pixel_lengths) { + if (pixel_lengths.hasOwnProperty(unit)) { + new_len = pixel_length / pixel_lengths[unit]; + new_string = `${new_len}${unit}`; + if (new_string.length < cur_string.length) { + cur_string = new_string; + } + } + } + return cur_string; +} + +// REQUIRED: A `run` function thats takes in current code and returns processed code. +function run(code) { + // `code` is your current code in the editor + var processedCode = code.replace(/(\d+)(vw|vh|pc|px|in|ex|em)/g, (match, $1,$2) => { + return getShortestUnit($1,$2); + }); + + // Return the final code + return processedCode; +} \ No newline at end of file