forked from Khan/khan-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspin.js
More file actions
47 lines (38 loc) · 1.52 KB
/
spin.js
File metadata and controls
47 lines (38 loc) · 1.52 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
$.extend(KhanUtil, {
spin: function(content) {
// First find all top-level blocks and spin them
var startingBracePos = -1;
var nestingLevel = 0;
for (var i = 0; i < content.length; i++) {
if (content.charAt(i) === "{") {
// We encounter our first "{"
if (startingBracePos === -1) {
startingBracePos = i;
// We are already inside a top-level block, this starts a nested block
} else {
nestingLevel++;
}
// We encounter a "}" and have seen a "{" before
} else if (content.charAt(i) === "}" && startingBracePos !== -1) {
// This is the closing brace for a top-level block
if (nestingLevel === 0) {
// Spin the top-level block
var spun = KhanUtil.spin(content.substring(startingBracePos + 1, i));
content = content.substring(0, startingBracePos) + spun + content.substring(i + 1);
i -= (i - startingBracePos) - spun.length + 1;
startingBracePos = -1;
// This brace closes a nested block
} else {
nestingLevel--;
}
}
}
return KhanUtil.randFromArray(content.split("|"));
}
});
$.fn.spin = function() {
this.find(".spin").each(function() {
var spun = KhanUtil.spin($(this).html());
$(this).html(spun);
});
};