简体   繁体   中英

eloquent javascript exercise 6.3

I am studying the Eloquent Javascript book.I am stuck at Exercise 6.3 .

I need a explanation for this line var end = reduce(Math.min, text.length, map(indexOrEnd, ["*", "{"])); and what is the purpose of var end? BTW i do understand how reduce works.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM