Hoc higher order functions

From openreachtech/hora-skills-ort-core · View interactive version

Hoc higher order functions is an AI agent skill from the GitHub repository openreachtech/hora-skills-ort-core. How higher-order functions such as `map()`, `filter()`, `reduce()` and `forEach()` are used: what becomes of their return value, what a callback holds and is named, how elements are treated, and what `reduce()` may not be bent into. Use when writing or reviewing a callback passed to an array method,

How to use this skill

Skill file

Higher-Order Functions

How a higher-order function is used once iteration has been written with one. That loops are not

written at all is settled by the statements convention; what follows is what the higher-order

form may and may not be.

Do not discard the return value of a higher-order function (except `Array#forEach()`)

// NG: using reduce solely for side effects and discarding the return value (a workaround to evade the sequential-processing prohibition)
array.reduce(
  (_, it) => {
    this.logger.log('value:', it)

    return _
  },
  null
)

// OK: express a side effect on each element with forEach
array.forEach(it => {
  this.logger.log(
    'value:',
    it
  )
})

`Array#forEach()` takes no assignment

keep forEach() from standing in for for / while**: a loop that assembles a result needs

somewhere to assign it, and with no assignment there is nothing for the callback to build.

// NG: assembling a result by pushing into an outer array inside forEach (violates the spirit of the sequential-processing prohibition)
const results = []
array.forEach(it => {
  results.push(transform(it))
})

// NG: assembling by setting into an outer Map
const map = new Map()
array.forEach(it => {
  map.set(it.id, transform(it))
})

// OK: assemble with map and receive the return value
const results = array
  .map(it => transform(it))

The callback passed to a higher-order function should basically be a single statement

a single responsibility).

// NG: the callback mixes multiple responsibilities (filtering + transformation)
const names = users.map(it => {
  if (!it.enabled) {
    return null
  }

  return it.name.toUpperCase()
})

// OK: split into filtering with filter and transformation with map, making each stage a single responsibility
const names = users
  .filter(it => it.enabled)
  .map(it => it.name.toUpperCase())

Do not casually extract the body of map() into a method

// NG: extracting the body of map into a method just to use if
values.map(it =>
  this.convertValue({ value: it }) // convertValue merely branches internally with if
)

// OK: separate the condition with filter, then map
values
  .filter(it => it.enabled)
  .map(it => it.value)

Treat all elements of an array equally in higher-order functions

Do not access array elements by subscript (`[]`)

// NG: accessing an individual element by subscript
const head = segments[0]

// OK: handle every element together with map / reduce, etc.
segments
  .map(it => this.normalize({ segment: it }))

Exception: first / last element

// NG
const head = segments[0]
const last = segments[segments.length - 1]

// OK: destructuring for the leading element (with a default), at(-1) for the last
const [head = ''] = segments
const last = segments.at(-1)

`reduce()` and `reduceRight()`

The accumulator is built out of what the elements hold. reduce() can be made to return

anything, which is why it is the method most often bent into something other than a fold: a

count, a side effect, a loop. Each of those is written with what was meant for it instead.

same thing whatever the elements are, so what it computes is something the collection already

has — its length, written longhand. A count is answered by the class holding the collection

(see the property-definition convention), and a name that promises a boolean does not return

one.

value section above: return the accumulator unchanged and discard the result, and what is left

is for without the keyword.

// NG: the callback never reads its element — this is the length, written longhand
hasValue () {
  return this.values.reduce(accumulator => accumulator + 1, 0)
}

// OK: the accumulator is built from what each element holds
const total = prices
  .reduce((total, it) => total + it.amount, 0)
// OK: omitting initialValue -> first element becomes the accumulator, second element onward is folded equally
const total = numbers
  .reduce((total, it) => total + it)

Naming the callback parameters

// OK: item parameter is it
const ids = samples
  .filter(it => it.enabled)
  .map(it => it.id)

// OK: name the inner nested item by meaning (outer it / inner user, etc.)
const names = teams
  .flatMap(it =>
    it.members.map(user => user.name)
  )

// OK: name the reduce accumulator by meaning (total for a running sum)
const total = prices
  .reduce((total, it) => total + it.amount, 0)
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.