Zhen Zhang


Eloquent JS: High-order Functions

June 13, 2026

1.Thus,we might fall into the pattern of the first recipe -- work out the precise steps the computer has to perform, one by one, biind to the higher-level concepts they express.

2.However, the body is now written as a function value which is wrapped in parentheses of the call to repeat. This is why it has to be closed with the closing brace and closing parenthesis. In case like this example, where the body is a single small expression, You could also omit the braces and write the loop on a single line.

repeat(5, i=> {
  labels.push(`Unit ${i + 1}`);
});
3.
function filter(array, test){
  let passed = [];
  for(let element of array){
    if(test(element)){
      passed.push(element);
    }
  }
  return passed;
}
4.SCRIPTS.filter(s=>s.living);.

5.
function map(array, transform){
  let mapped = [];
  for(let element of array){
    mapped.push(transform(element));
  }
  return mapped;
}
6.
function reduce(array, combine, start){
  let current = start;
  for(let element of array){
    current = combine(current, element);
  }
  return current;
}

[1, 2, 3, 4].reduce((a, b)=> a+b)
7.
script.range.some([from, to]=>{
  return code>=from&&code<=to;
})
8.unfortunately, obvious operations on JavaScript strings, such as getting their length through the length property and accessing their content using square bracket, deal only with code unit.

9.JavaScript's charCodeAt method give you a code unit, not a full character code. The codePointAt method, added later does give a full Unicode character so we could use that to get character from a string. But the arguement passed to codePointAt is still an index into the sequence of code units. To run over all characters in a string, we'd still need to deal with the question of whether a character takes up one or two code unit.

10.I mentioned that a for/of loop can also be used on strings like codePointAt, this type of loop was introduced at a time when people were acutely aware of the problems with UTF-16. when you use it to loop over string, it gives you real characters, not code units.

11.
function countBy(items, groupName){
  let counts = [];
  for(let item of items){
    let name = groupName[item];
    let known = counts.find(s => s.name ==name);
    if(!known) {
      counts.push({name, count:1});
    } else {
      known.count++;
    }
  }
  return counts;
}

function textScript(text){
  let scripts = countBy(text, char => {
    let script = characterScript(char.codePointAt(0));
    return script?script.name: "none";
  }).filter(s=>s.name!="none");
}


About Privacy Home