]> git.sommitrealweird.co.uk Git - cssbattle.git/blob - unit_replacement.js
Rename from .txt to .js, as they're all JavaScript
[cssbattle.git] / unit_replacement.js
1 // 1ch -> 8px
2 // 1pc -> 12pt -> 1/6in -> 16px
3 // 1vw -> 4px
4 // 1vh -> 3px
5 // 1in -> 96px
6 // 1ex -> 7.16px (useful, right?!)
7 // 1em -> 16px - we'll just use pc for this instead
8 // 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'
9
10 pixel_lengths = {
11   "ch": 8,
12   "pc": 16,
13   "vw":4,
14   "vh":3,
15   "in": 96,
16   "ex":7.16,
17   "em":16,
18   "px":1
19 };
20
21 function getShortestUnit(length,unit) {
22   cur_string = `${length}${unit}`;
23   pixel_length = 0;
24     if (pixel_lengths.hasOwnProperty(unit)) {
25       pixel_length = length * pixel_lengths[unit];
26     }
27     else {
28       return cur_string;
29     }
30     for (unit in pixel_lengths) {
31       if (pixel_lengths.hasOwnProperty(unit)) {
32         new_len = pixel_length / pixel_lengths[unit];
33         new_string = `${new_len}${unit}`;
34         if (new_string.length < cur_string.length) {
35           cur_string = new_string;
36         }
37       }
38     }
39   return cur_string;
40 }
41
42 // REQUIRED: A `run` function thats takes in current code and returns processed code.
43 function run(code) {
44   // `code` is your current code in the editor
45   var processedCode = code.replace(/(\d+)(vw|vh|pc|px|in|ex|em)/g, (match, $1,$2) => {
46    return getShortestUnit($1,$2);
47   });
48                                    
49   // Return the final code
50   return processedCode;
51 }