splitAtDelimiters.js (2959B)
1 /* eslint no-constant-condition:0 */ 2 const findEndOfMath = function(delimiter, text, startIndex) { 3 // Adapted from 4 // https://github.com/Khan/perseus/blob/master/src/perseus-markdown.jsx 5 let index = startIndex; 6 let braceLevel = 0; 7 8 const delimLength = delimiter.length; 9 10 while (index < text.length) { 11 const character = text[index]; 12 13 if (braceLevel <= 0 && 14 text.slice(index, index + delimLength) === delimiter) { 15 return index; 16 } else if (character === "\\") { 17 index++; 18 } else if (character === "{") { 19 braceLevel++; 20 } else if (character === "}") { 21 braceLevel--; 22 } 23 24 index++; 25 } 26 27 return -1; 28 }; 29 30 const splitAtDelimiters = function(startData, leftDelim, rightDelim, display) { 31 const finalData = []; 32 33 for (let i = 0; i < startData.length; i++) { 34 if (startData[i].type === "text") { 35 const text = startData[i].data; 36 37 let lookingForLeft = true; 38 let currIndex = 0; 39 let nextIndex; 40 41 nextIndex = text.indexOf(leftDelim); 42 if (nextIndex !== -1) { 43 currIndex = nextIndex; 44 finalData.push({ 45 type: "text", 46 data: text.slice(0, currIndex), 47 }); 48 lookingForLeft = false; 49 } 50 51 while (true) { 52 if (lookingForLeft) { 53 nextIndex = text.indexOf(leftDelim, currIndex); 54 if (nextIndex === -1) { 55 break; 56 } 57 58 finalData.push({ 59 type: "text", 60 data: text.slice(currIndex, nextIndex), 61 }); 62 63 currIndex = nextIndex; 64 } else { 65 nextIndex = findEndOfMath( 66 rightDelim, 67 text, 68 currIndex + leftDelim.length); 69 if (nextIndex === -1) { 70 break; 71 } 72 73 finalData.push({ 74 type: "math", 75 data: text.slice( 76 currIndex + leftDelim.length, 77 nextIndex), 78 rawData: text.slice( 79 currIndex, 80 nextIndex + rightDelim.length), 81 display: display, 82 }); 83 84 currIndex = nextIndex + rightDelim.length; 85 } 86 87 lookingForLeft = !lookingForLeft; 88 } 89 90 finalData.push({ 91 type: "text", 92 data: text.slice(currIndex), 93 }); 94 } else { 95 finalData.push(startData[i]); 96 } 97 } 98 99 return finalData; 100 }; 101 102 module.exports = splitAtDelimiters;