0

code not working and compiler says "ReferenceError: range is not defined"

code is copied from this famous book:https://eloquentjavascript.net/05_higher_order.html#c_EiK2Y8M/Mh code:

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    console.log(action(...range(0, i)));
  }
}
repeat(5, Math.max);

I tried let range = new Range(); but it wasn't working

xuan xose
  • 19
  • 4
  • See https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp – James Apr 07 '23 at 17:20
  • 1
    There is not `Range` in javascript. – Gabriele Petrioli Apr 07 '23 at 17:23
  • The book makes no claim that `range` exists by itself in JS. And certainly no claim is made that `new Range()` is a thing. The text just illustrates usage of a higher order function without supplying the implementation for it. It even says this: "*The definitions of this vocabulary (the functions sum and range) will still involve loops, counters, and other incidental details. But because they are expressing simpler concepts than the program as a whole, they are easier to get right.*" – VLAZ Apr 07 '23 at 17:46
  • 2
    In chapter 4 you were supposed to write a range function... Did you skip chapter 4? – epascarello Apr 07 '23 at 18:23

1 Answers1

-1

Try for 0...n-1, try Array(n).keys()

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    console.log(action(...Array(i).keys()));
  }
}
repeat(5, Math.max);

The JS Range feature is for text

const paragraphs = document.querySelectorAll("p");

const range = new Range();
range.setStartBefore(paragraphs[1]);
range.setEndAfter(paragraphs[2]);

const selection = window.getSelection();
selection.addRange(range);
<p>One</p>
<p>Two - this will get selected</p>
<p>Three - this will get selected</p>
<p>Four</p>
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26