Universal metric translator

Automatically converts imperial units to metric units

  1. // ==UserScript==
  2. // @name Universal metric translator
  3. // @namespace https://bennyjacobs.nl/userscripts/Universal-metric-translator
  4. // @description Automatically converts imperial units to metric units
  5. // @license BSD-3-Clause
  6. // @include about:addons
  7. // @include *
  8. // @version 2.1.3
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. /*
  13. BSD 3-Clause License
  14.  
  15. Copyright (c) 2017, Benny Jacobs
  16. All rights reserved.
  17.  
  18. Redistribution and use in source and binary forms, with or without
  19. modification, are permitted provided that the following conditions are met:
  20.  
  21. * Redistributions of source code must retain the above copyright notice, this
  22. list of conditions and the following disclaimer.
  23.  
  24. * Redistributions in binary form must reproduce the above copyright notice,
  25. this list of conditions and the following disclaimer in the documentation
  26. and/or other materials provided with the distribution.
  27.  
  28. * Neither the name of the copyright holder nor the names of its
  29. contributors may be used to endorse or promote products derived from
  30. this software without specific prior written permission.
  31.  
  32. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  33. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  34. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  35. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  36. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  37. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  38. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  40. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43.  
  44. // Flags: global, insensitive
  45. const createTransformationRegEx = (unit) => new RegExp(`(?:^|\\s)((\\d\\s)?[0-9]+(?:\\.[0-9]+)?(?:/[0-9]+(?:\\.[0-9]+)?)?)\\s*(${unit})\\b(?!(\\s\\[))`,"i");
  46.  
  47. // Sources:
  48. // https://en.wikipedia.org/wiki/Imperial_units
  49. // https://en.wikipedia.org/wiki/Metre
  50. // https://en.wikipedia.org/wiki/Square_metre
  51. // https://en.wikipedia.org/wiki/Litre
  52. const tranformationTable = [
  53.  
  54. // Temperature
  55. {
  56. from: '(?:F|fahrenheit|fahrenheits|degrees F|degrees fahrenheit)',
  57. to: '℃',
  58. convert: function(fahrenheits){
  59. return ((fahrenheits - 32) / 1.8).toFixed(2);
  60. }
  61. },
  62.  
  63. // Distance
  64. {
  65. from: 'thou',
  66. to: 'm',
  67. convert: 25.4 * 1e-6,
  68. }, {
  69. from: '(?:inch(?:es|e)?)',
  70. to: 'm',
  71. convert: 25.4 * 1e-3,
  72. }, {
  73. from: '(?:(?:feets?|foot))',
  74. to: 'm',
  75. convert: 0.3048,
  76. }, {
  77. from: '(?:yards?|yd)',
  78. to: 'm',
  79. convert: 0.9144,
  80. }, {
  81. from: 'chains?',
  82. to: 'm',
  83. convert: 20.1168,
  84. }, {
  85. from: '(?:furlongs?|fur)',
  86. to: 'm',
  87. convert: 201.168,
  88. }, {
  89. from: 'miles?',
  90. to: 'm',
  91. convert: 1.609344 * 1e3,
  92. }, {
  93. from: 'leagues?',
  94. to: 'm',
  95. convert: 4.828032 * 1e3,
  96. },
  97.  
  98. // Maritime distances
  99. {
  100. from: '(?:fathoms?|ftm)',
  101. to: 'm',
  102. convert: 1.853184,
  103. }, {
  104. from: 'cables?',
  105. to: 'm',
  106. convert: 185.3184,
  107. }, {
  108. from: 'nautical\\smiles?', // Note: two backslashes as we are escaping a javascript string
  109. to: 'm',
  110. convert: 1.853184 * 1e3,
  111. },
  112.  
  113. // Gunter's survey units (17th century onwards)
  114. {
  115. from: 'link',
  116. to: 'm',
  117. convert: 0.201168,
  118. }, {
  119. from: 'rod',
  120. to: 'm',
  121. convert: 5.0292,
  122. }, {
  123. from: 'chain',
  124. to: 'm',
  125. convert: 20.1168,
  126. },
  127.  
  128. // Area
  129. {
  130. from: 'acres?',
  131. to: 'km²',
  132. convert: 4.0468564224,
  133. },
  134.  
  135. // Volume
  136. {
  137. from: '(?:fluid ounces?|fl oz)',
  138. to: 'L',
  139. convert: 28.4130625 * 1e-3,
  140. }, {
  141. from: 'gill?',
  142. to: 'L',
  143. convert: 142.0653125 * 1e-3,
  144. }, {
  145. from: '(?:pints?|pt)',
  146. to: 'L',
  147. convert: 0.56826125,
  148. }, {
  149. from: 'quarts?',
  150. to: 'L',
  151. convert: 1.1365225,
  152. }, {
  153. from: 'gal(?:lons?)?',
  154. to: 'L',
  155. convert: 4.54609,
  156. },
  157.  
  158. //Weight
  159. {
  160. from: 'grains?',
  161. to: 'g',
  162. convert: 64.79891 * 1e-3,
  163. }, {
  164. from: 'drachm',
  165. to: 'g',
  166. convert: 1.7718451953125,
  167. }, {
  168. from: '(?:ounces?|oz)',
  169. to: 'g',
  170. convert: 28.349523125,
  171. }, {
  172. // from: 'lbs?|pounds?', // Pound is ambiguous. It can be a currency. Therefore we don't touch it.
  173. // Actually, since it would be displayed as
  174. // "It costs 1 pound [453.59 g]."
  175. // the metric translation can just be ignored by the reader.
  176. // I'm leaving it out anyways. lbs is usually used in written text anyways so it covers most cases.
  177. from: 'lbs?',
  178. to: 'g',
  179. convert: 453.59,
  180. }, {
  181. from: 'stones?',
  182. to: 'g',
  183. convert: 6.35029318 * 1e3,
  184. }, {
  185. from: 'quarters?',
  186. to: 'g',
  187. convert: 12.70058636 * 1e3,
  188. }, {
  189. from: 'hundredweights?',
  190. to: 'g',
  191. convert: 50.80234544 * 1e3,
  192. },
  193. // A 'ton' might belong here, but there exist a metric ton and a imperial ton.
  194. // Qon commment: A metric ton is sometimes spelled metric tonne or just tonne though.
  195. // https://en.wikipedia.org/wiki/Ton
  196. ];
  197.  
  198. tranformationTable.forEach(function (transformationRule) {
  199. transformationRule.regex = createTransformationRegEx(transformationRule.from);
  200. });
  201.  
  202. const replaceSubstring = function(originalText, index, length, replacement) {
  203. var before_substring = originalText.substring(0, index);
  204. var after_substring = originalText.substring(index+length);
  205. return before_substring + replacement + after_substring;
  206. };
  207.  
  208. const round_number = (num, dec) => {
  209. return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
  210. }
  211.  
  212. // The transformText function is idempotent.
  213. // Repeated calls on the output will do nothing. Only the first invocation has any effect.
  214. // The input will be returned on repeated calls.
  215. const transformText = (text) => {
  216. tranformationTable.forEach((transformationRule) => {
  217. transformationRule.regex.lastIndex = 0;
  218. for(var match; match = transformationRule.regex.exec(text);) {
  219.  
  220. // console.log(match, parseFloat(match[1], 10))
  221. var old_value, new_value;
  222.  
  223. // if the number is written like 1 1/4 instead of 1.25 then:
  224. if(/\//.test(match[1])) {
  225. old_value = match[1].split(' ')
  226. if(old_value.length == 2)
  227. {
  228. var a = old_value[1].split('/')
  229. old_value[1] = parseFloat(a[0].replace(/,/g, ''), 10) / parseFloat(a[1].replace(/,/g, ''), 10)
  230. old_value = parseFloat(old_value[0].replace(/,/g, ''), 10) + old_value[1]
  231. }
  232. else
  233. {
  234. var a = old_value[0].split('/')
  235. old_value = parseFloat(a[0].replace(/,/g, ''), 10) / parseFloat(a[1].replace(/,/g, ''), 10)
  236. }
  237. } else {
  238. old_value = parseFloat(match[1].replace(/,/g, ''), 10)
  239. }
  240. if(typeof transformationRule.convert == 'function') {
  241. new_value = transformationRule.convert(old_value);
  242. } else {
  243. new_value = old_value * transformationRule.convert;
  244. }
  245. var new_unit = transformationRule.to;
  246. if(new_unit === 'g' || new_unit === 'L' || new_unit === 'm')
  247. {
  248. if(new_value > 1e12) {
  249. new_unit = 'T' + new_unit
  250. new_value /= 1e12
  251. } else if (new_value > 1e9) {
  252. new_unit = 'G' + new_unit
  253. new_value /= 1e9
  254. } else if (new_value > 1e6) {
  255. // if(new_unit === 'g') new_unit = 'tonne' else
  256. new_unit = 'M' + new_unit
  257. new_value /= 1e6
  258. } else if (new_value > 1e3) {
  259. new_unit = 'k' + new_unit
  260. new_value /= 1e3
  261. } else if (new_value < 1e-9) {
  262. new_unit = 'p' + new_unit
  263. new_value /= 1e-12
  264. } else if (new_value < 1e-6) {
  265. new_unit = 'n' + new_unit
  266. new_value /= 1e-9
  267. } else if (new_value < 1e-3) {
  268. new_unit = 'µ' + new_unit
  269. new_value /= 1e-6
  270. } else if (new_value < 1e-2) {
  271. new_unit = 'm' + new_unit
  272. new_value /= 1e-3
  273. } else if (new_value < 1 && (new_unit !== 'g')) {
  274. new_unit = 'c' + new_unit
  275. new_value /= 1e-2
  276. }
  277. }
  278. // function significantDigits(old, new) {
  279. // old.replace(/^[^1-9]*/, '').replace(/\D/g, '').length
  280. // }
  281. new_value = round_number(new_value, 2)
  282. if(true) {
  283. var new_substring =
  284. match[0]
  285. + ' ['
  286. + new_value
  287. + " "
  288. + new_unit
  289. + ']'
  290. } else {
  291. var new_substring =
  292. new_value
  293. + " "
  294. + new_unit
  295. + ' ['
  296. + match[0]
  297. + ']'
  298. }
  299.  
  300. text = replaceSubstring(text, match.index, match[0].length, new_substring );
  301. // Move the matching index past whatever we have replaced.
  302. // Note: The replacement can be shorter or longer.
  303. transformationRule.regex.lastIndex = transformationRule.regex.lastIndex + (new_substring.length - match[0].length);
  304. }
  305. });
  306. return text;
  307. };
  308.  
  309. // conversation => convert. Because this has nothing to do with discussions.
  310. // Rounding moved so it happens only immediatly before being inserted into
  311. // the document.
  312. // If it's done as the first step we lose a lot(!) of precision.
  313. // As an example 0.004 inches was rounded to 0, then converted to metric
  314. // (still 0) and then inserted. Extremely wrong.
  315. // Also 0.01497 miles gets rounded to 0.01 (33% less!) and then converted to
  316. // metric. The result is 0.01 * 1.609344 = 0.01609344, way more digits than
  317. // before we started! This looks extremely precise with 8 significant digits,
  318. // but it's actually only 1 since began by completely destroying our initial
  319. // number. Correct convertion should have the same number of significant
  320. // digits as the initial number (4). But some numbers, like 1 inch, might
  321. // actually be exactly 1 inch, or 2.54 cm. Rounding 1 inch to 3 cm seems a
  322. // bit wrong. It's unusual that 1 inch is written like "1.00 inches" even
  323. // if that precision is intended. So a flat rounding to 2 decimals after(!)
  324. // choosing a good prefix (and scaling our number by the prefix) should work
  325. // for most cases.
  326.  
  327. const handleTextNode = (textNode) => {
  328. var transformedText = transformText(textNode.nodeValue);
  329. if(textNode.nodeValue != transformedText)
  330. textNode.nodeValue = transformedText;
  331. };
  332.  
  333. // Travel the node(s) in a recursive fashion.
  334. const walk = (node) => {
  335. var child, next;
  336.  
  337. switch (node.nodeType) {
  338. case 1: // Element
  339. case 9: // Document
  340. case 11: // Document fragment
  341. child = node.firstChild;
  342. while (child) {
  343. next = child.nextSibling;
  344. walk(child);
  345. child = next;
  346. }
  347. break;
  348. case 3: // Text node
  349. handleTextNode(node);
  350. break;
  351. default:
  352. break;
  353. }
  354. };
  355.  
  356. const MutationObserver = (window.MutationObserver || window.WebKitMutationObserver);
  357. var observer = new MutationObserver((mutations) => {
  358. mutations.forEach((mutation) => {
  359. if(mutation.type == 'childList') {
  360. for (var i = 0; i < mutation.addedNodes.length; ++i) {
  361. walk(mutation.addedNodes[i]);
  362. }
  363. } else if (mutation.type == 'characterData') {
  364. handleTextNode(mutation.target);
  365. }
  366. });
  367. });
  368.  
  369. observer.observe(document, {
  370. childList: true,
  371. characterData: true,
  372. subtree: true,
  373. });
  374.  
  375. walk(document.body);