-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAmlToHtml.js
More file actions
76 lines (66 loc) · 2.26 KB
/
AmlToHtml.js
File metadata and controls
76 lines (66 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var AMLTranslator = (function () {
// This will act as a traditional stack data structure
// Since JS doesnt support stacks, we will use an array and just push and pop accordingly
var elementStack = [];
// aml dictionary for easier lookup for translating
// alternatively we could include another dictionary for other translations
var amlDict = {
'^': 'openingElement',
'!': 'closingElement',
'%': 'STRONG',
'~': 'EM'
};
// The main function that accepts the test cases
var translate = function(input) {
var output = [];
// Split the input
var amlArray = input.split('');
// search through the array each character in the string
amlArray.forEach( function(element, index) {
// get the next element
var nextElement = amlArray[index+1];
//get the element two down
var elementAfterNext = amlArray[index+2];
if(amlDict[element] === 'openingElement'){
output.push(amlToHtml(nextElement, elementAfterNext));
}
//check if the key exists and check if the character is should be escaped
else if(!amlDict[element] || !amlDict[amlArray[index-1]]) {
output.push(element);
}
});
return output.join('');
};
// This function will be used for translating aml to html
// Alternatively we could have other functions for different translations
var amlToHtml = function(nextElement, elementAfterNext){
// If the next element is the closing element
if(amlDict[nextElement] === 'closingElement') {
var closingElement = amlDict[elementAfterNext];
var top = elementStack[0];
var index = elementStack.indexOf(closingElement);
var output;
// then check the stack to see if the element is closing an already open one
if(elementStack.includes(closingElement) && closingElement !== top){
// if it is close the current element and open the new one
output = `</${top}></${closingElement}><${top}>`;
}
// otherwise just close it without opening a new one
else {
output = `</${closingElement}>`;
}
//remove it from the stack
elementStack.splice(index, 1);
}
else {
// push to the top of the stack
elementStack.unshift(amlDict[nextElement]);
output = `<${amlDict[nextElement]}>`;
}
return output;
}
return { "translate": translate };
}());
if(module.exports) {
module.exports = AMLTranslator;
}