-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrenderQuery.js
51 lines (40 loc) · 1.57 KB
/
renderQuery.js
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
/*
You're given a function findNamedEntities(s). Given a string representing an English question, it returns a series of spans representing noun phrases within the question.
E.g.
findNamedEntities("What years did Barack Obama attend Harvard?")
> [[15, 27], [35, 42]]
Write a function renderQuery which renders the query to the DOM with the entities underlined.
E.g.
<div id="query">What years did <u>Barack Obama</u> attend <u>Harvard</u></div>
*/
var wrapQueryWithElement = function(query, el) {
var elStart = '<'+el+'>';
var elEnd = '</'+el+'>';
var modifier = elStart.length + elEnd.length;
var indexModifier = function(x) { return modifier * x; };
var newStr = query.value;
var indices = query.indices;
for(var i=0; i < indices.length; i++) {
var currentIndexModifier = indexModifier(i);
var startIndex = indices[i][0] + currentIndexModifier;
var endIndex = indices[i][1] + currentIndexModifier;
var strBefore = newStr.slice(0, startIndex);
var strReplace = elStart + newStr.substring(startIndex, endIndex) + elEnd;
var strAfter = newStr.slice(endIndex);
newStr = strBefore+strReplace+strAfter;
}
query.value = newStr;
return query;
};
var renderQuery = function(el, query) {
el.innerHTML=query.value;
}
var strQuery = 'What years did Barack Obama attend Harvard?';
var namedEntitiesIndices = [[15, 27], [35, 42]];
var namedEntitiesQuery = {
value: strQuery,
indices: namedEntitiesIndices
};
var resultQuery = wrapQueryWithElement(namedEntitiesQuery, 'u');
console.log(resultQuery);
renderQuery(document.getElementById('query'), resultQuery);