]> git.sommitrealweird.co.uk Git - cssbattle.git/blob - unit_replacement.js
Add license
[cssbattle.git] / unit_replacement.js
1 /*
2 Permission to use, copy, modify, and/or distribute this software for
3 any purpose with or without fee is hereby granted.
4
5         THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
6 WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
7 OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
8 FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
9 DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
10 AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
11 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12 */
13
14 // 1ch -> 8px
15 // 1pc -> 12pt -> 1/6in -> 16px
16 // 1vw -> 4px
17 // 1vh -> 3px
18 // 1in -> 96px
19 // 1ex -> 7.16px (useful, right?!)
20 // 1em -> 16px - we'll just use pc for this instead
21 // 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'
22
23 pixel_lengths = {
24   "ch": 8,
25   "pc": 16,
26   "vw":4,
27   "vh":3,
28   "in": 96,
29   "ex":7.16,
30   "em":16,
31   "px":1
32 };
33
34 function getShortestUnit(length,unit) {
35   cur_string = `${length}${unit}`;
36   pixel_length = 0;
37     if (pixel_lengths.hasOwnProperty(unit)) {
38       pixel_length = length * pixel_lengths[unit];
39     }
40     else {
41       return cur_string;
42     }
43     for (unit in pixel_lengths) {
44       if (pixel_lengths.hasOwnProperty(unit)) {
45         new_len = pixel_length / pixel_lengths[unit];
46         new_string = `${new_len}${unit}`;
47         if (new_string.length < cur_string.length) {
48           cur_string = new_string;
49         }
50       }
51     }
52   return cur_string;
53 }
54
55 // REQUIRED: A `run` function thats takes in current code and returns processed code.
56 function run(code) {
57   // `code` is your current code in the editor
58   var processedCode = code.replace(/(\d+)(vw|vh|pc|px|in|ex|em)/g, (match, $1,$2) => {
59    return getShortestUnit($1,$2);
60   });
61                                    
62   // Return the final code
63   return processedCode;
64 }