[英]eloquent javascript exercise 6.3
I am studying the Eloquent Javascript book.I am stuck at Exercise 6.3 . 我正在学习Eloquent Javascript书籍。我坚持练习6.3 。
I need a explanation for this line var end = reduce(Math.min, text.length, map(indexOrEnd, ["*", "{"]));
我需要对此行的解释
var end = reduce(Math.min, text.length, map(indexOrEnd, ["*", "{"]));
and what is the purpose of var end? var end的目的是什么? BTW i do understand how reduce works.
顺便说一句,我确实知道reduce是如何工作的。
I have seen couple of other threads about it but not many answers.Thanks in advance. 我已经看到了其他一些相关话题,但答案并不多。
here is the code - 这是代码-
function splitParagraph(text) {
function indexOrEnd(character) {
var index = text.indexOf(character);
return index == -1 ? text.length : index;
}
function takeNormal() {
var end = reduce(Math.min, text.length,
map(indexOrEnd, ["*", "{"]));
var part = text.slice(0, end);
text = text.slice(end);
return part;
}
function takeUpTo(character) {
var end = text.indexOf(character, 1);
if (end == -1)
throw new Error("Missing closing '" + character + "'");
var part = text.slice(1, end);
text = text.slice(end + 1);
return part;
}
var fragments = [];
while (text != "") {
if (text.charAt(0) == "*")
fragments.push({type: "emphasised",
content: takeUpTo("*")});
else if (text.charAt(0) == "{")
fragments.push({type: "footnote",
content: takeUpTo("}")});
else
fragments.push({type: "normal",
content: takeNormal()});
}
return fragments;
}
The array that is mapped and reduced over only contains two items (not a big or dynamic number), so we can easily inline the calls: 映射并缩小的数组仅包含两项(不是大数或动态数),因此我们可以轻松地内联调用:
reduce(Math.min, text.length, map(indexOrEnd, ["*", "{"]))
= reduce(Math.min, text.length, [indexOrEnd("*"), indexOrEnd("{")])
= Math.min(Math.min(text.length, indexOrEnd("*")), indexOrEnd("{"))
= Math.min(text.length, indexOrEnd("*"), indexOrEnd("{"))
So, end
will be the index of the first occurrence of the *
or {
characters, or the end of the text if none of them appears. 因此,
end
将是*
或{
字符的第一个出现的索引,如果没有字符出现,则为文本的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.