LoginSignup
0
0

More than 1 year has passed since last update.

再帰処理

Last updated at Posted at 2022-03-26

最近、ちょっとボケ気味なのでメモっとく。

children に子要素を再帰的に持つデータに対しての処理関数。

データ構造
let item = {
 children = [],
 ...parameter,
}
let items = [item]
recursive(items, args) {
  let return_value = null
  items.forEach(item => {
    return_value = proc_statement(item, args)
    if (!exit_recursive_condition(item, args)) {
      // 条件に一致しなければ子要素に対して処理をする
      return_value = recursive(item.children, args)
    }
  });
  return return_value
}
exit_recursive_condition(item, args) {
  // 再帰処理を抜ける条件
  return item.parameter == args
}
proc_statement(item, args) {
  // 要素に対する処理
  return item
}

args は再帰処理を抜ける条件や要素に対して処理を行うための引数。
全ての要素に対して処理を行うのであれば exit_recursive_condition()は不要でforEach をmapに変えればよいかと。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0