Command Palette

Search for a command to run...

Назад к скиллам
скилл № 20314

hoc-higher-order-functions

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…

БесплатноБез исполняемых скриптов
openreachtechот openreachtech★ 17 звёзд на GitHub

Установить hoc-higher-order-functions в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

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())

  • Do not discard the return value of a higher-order function (map / filter / reduce, etc.). If the return value is neither assigned to a variable nor used as a return value, that code is prohibited.
  • If the sole purpose is a side effect on each element (such as logging), use Array#forEach(). forEach is a higher-order function that assumes an undefined return value, so it is exempt from this rule.
  • In particular, using reduce solely for side effects, returning the accumulator unchanged and discarding the return value, is a hack to evade the prohibition on sequential processing, and is prohibited.
// 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

  • ESLint prohibits writing an assignment statement inside Array#forEach(). The reason is to 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.
  • Also, if statements are prohibited inside higher-order functions (express branching with filter or a conditional expression).
  • Therefore, what can be written with forEach is limited to a pure side effect that involves no assignment or branching (such as logging or calling an external API).
  • An implementation that processes all elements equally while building up a result by pushing elements into an array or Map defined with let/const in the outer scope violates the spirit of the sequential-processing prohibition and is not allowed. push() / set() are not assignment statements, so they slip past ESLint, but in substance this is an imperative loop and amounts to a workaround. Express iteration that assembles a result with map / filter / reduce / Array.from, etc., and receive it as a return value.
// 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

  • The body of a function (callback) passed as an argument to a higher-order function should ideally consist of only a single statement.
  • Even when writing multiple statements, limit it to what can be expressed as a single method name (i.e., extracted as a single responsibility).
  • When there are multiple responsibilities, make full use of Array#filter() / Array#map() to split each stage into 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

  • Do not casually extract the body of the higher-order function passed to Array#map() into a method.
  • If the reason is "I want to use an if statement but can't inside a higher-order function," first consider using .filter().map().
// 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

  • When handling an array with a higher-order function such as map / filter / forEach, do not special-case a particular element (such as the first one) by checking index. Transform/process all elements equally with the same logic.
  • Even when it looks like you want to change the result only for the first element, first consider whether "processing all elements equally and absorbing the difference in a batch step such as after joining" is
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл hoc-higher-order-functions?

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, or when about to reach an element by index. Loops themselves belong to the statements convention; a collection a property holds, to the property-definition convention.

Как установить скилл hoc-higher-order-functions?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hoc-higher-order-functions запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить hoc-higher-order-functions с