OLD | NEW |
(Empty) | |
| 1 /*! |
| 2 * `JSON.minify()` |
| 3 * This version does not use regular expressions. |
| 4 * |
| 5 * Copyright 2011, Kyle Simpson. |
| 6 * Copyright 2012, Kit Cambridge. |
| 7 * |
| 8 * Released under the MIT License. |
| 9 */ |
| 10 |
| 11 ;(function () { |
| 12 var JSON = this.JSON; |
| 13 |
| 14 // Create the global JSON object if it doesn't exist. |
| 15 if (Object(JSON) !== JSON) { |
| 16 JSON = this.JSON = {}; |
| 17 } |
| 18 |
| 19 JSON.minify = function (source) { |
| 20 var index = 0, length = source.length, result = "", symbol, position; |
| 21 while (index < length) { |
| 22 symbol = source.charAt(index); |
| 23 switch (symbol) { |
| 24 // Ignore whitespace tokens. According to ES 5.1 section 15.12.1.1, |
| 25 // whitespace tokens include tabs, carriage returns, line feeds, and |
| 26 // space characters. |
| 27 // ----------------------------------------------------------------- |
| 28 case "\t": |
| 29 case "\r": |
| 30 case "\n": |
| 31 case " ": |
| 32 index += 1; |
| 33 break; |
| 34 // Ignore line and block comments. |
| 35 // ------------------------------- |
| 36 case "/": |
| 37 symbol = source.charAt(index += 1); |
| 38 switch (symbol) { |
| 39 // Line comments. |
| 40 // ------------- |
| 41 case "/": |
| 42 position = source.indexOf("\n", index); |
| 43 if (position < 0) { |
| 44 // Check for CR-style line endings. |
| 45 position = source.indexOf("\r", index); |
| 46 } |
| 47 index = position > -1 ? position : length; |
| 48 break; |
| 49 // Block comments. |
| 50 // --------------- |
| 51 case "*": |
| 52 position = source.indexOf("*/", index); |
| 53 if (position > -1) { |
| 54 // Advance the scanner's position past the end of the comment. |
| 55 index = position += 2; |
| 56 break; |
| 57 } |
| 58 throw SyntaxError("Unterminated block comment."); |
| 59 default: |
| 60 throw SyntaxError("Invalid comment."); |
| 61 } |
| 62 break; |
| 63 // Parse strings separately to ensure that any whitespace characters and |
| 64 // JavaScript-style comments within them are preserved. |
| 65 // --------------------------------------------------------------------- |
| 66 case '"': |
| 67 position = index; |
| 68 while (index < length) { |
| 69 symbol = source.charAt(index += 1); |
| 70 if (symbol == "\\") { |
| 71 // Skip past escaped characters. |
| 72 index += 1; |
| 73 } else if (symbol == '"') { |
| 74 break; |
| 75 } |
| 76 } |
| 77 if (source.charAt(index) == '"') { |
| 78 result += source.slice(position, index += 1); |
| 79 break; |
| 80 } |
| 81 throw SyntaxError("Unterminated string."); |
| 82 // Preserve all other characters. |
| 83 // ------------------------------ |
| 84 default: |
| 85 result += symbol; |
| 86 index += 1; |
| 87 } |
| 88 } |
| 89 return result; |
| 90 }; |
| 91 }).call(this); |
OLD | NEW |