utils.js (2344B)
1 /** 2 * This file contains a list of utility functions which are useful in other 3 * files. 4 */ 5 6 /** 7 * Provide an `indexOf` function which works in IE8, but defers to native if 8 * possible. 9 */ 10 const nativeIndexOf = Array.prototype.indexOf; 11 const indexOf = function(list, elem) { 12 if (list == null) { 13 return -1; 14 } 15 if (nativeIndexOf && list.indexOf === nativeIndexOf) { 16 return list.indexOf(elem); 17 } 18 const l = list.length; 19 for (let i = 0; i < l; i++) { 20 if (list[i] === elem) { 21 return i; 22 } 23 } 24 return -1; 25 }; 26 27 /** 28 * Return whether an element is contained in a list 29 */ 30 const contains = function(list, elem) { 31 return indexOf(list, elem) !== -1; 32 }; 33 34 /** 35 * Provide a default value if a setting is undefined 36 */ 37 const deflt = function(setting, defaultIfUndefined) { 38 return setting === undefined ? defaultIfUndefined : setting; 39 }; 40 41 // hyphenate and escape adapted from Facebook's React under Apache 2 license 42 43 const uppercase = /([A-Z])/g; 44 const hyphenate = function(str) { 45 return str.replace(uppercase, "-$1").toLowerCase(); 46 }; 47 48 const ESCAPE_LOOKUP = { 49 "&": "&", 50 ">": ">", 51 "<": "<", 52 "\"": """, 53 "'": "'", 54 }; 55 56 const ESCAPE_REGEX = /[&><"']/g; 57 58 function escaper(match) { 59 return ESCAPE_LOOKUP[match]; 60 } 61 62 /** 63 * Escapes text to prevent scripting attacks. 64 * 65 * @param {*} text Text value to escape. 66 * @return {string} An escaped string. 67 */ 68 function escape(text) { 69 return ("" + text).replace(ESCAPE_REGEX, escaper); 70 } 71 72 /** 73 * A function to set the text content of a DOM element in all supported 74 * browsers. Note that we don't define this if there is no document. 75 */ 76 let setTextContent; 77 if (typeof document !== "undefined") { 78 const testNode = document.createElement("span"); 79 if ("textContent" in testNode) { 80 setTextContent = function(node, text) { 81 node.textContent = text; 82 }; 83 } else { 84 setTextContent = function(node, text) { 85 node.innerText = text; 86 }; 87 } 88 } 89 90 /** 91 * A function to clear a node. 92 */ 93 function clearNode(node) { 94 setTextContent(node, ""); 95 } 96 97 module.exports = { 98 contains: contains, 99 deflt: deflt, 100 escape: escape, 101 hyphenate: hyphenate, 102 indexOf: indexOf, 103 setTextContent: setTextContent, 104 clearNode: clearNode, 105 };