How to apply a function to all selected cells

I’m trying to write an extension that needs to apply some stuff on all the selected cells (or the active cell if no multiple selection is done)

As a first attempt I have written this,

export const apply_on_cells = (
  notebookTracker: INotebookTracker,
  scope: Scope,
  to_apply: (cell: Cell) => void,
) => {
      const { anchor, head } = notebook.getContiguousSelection()
      // when only one cell is selected/active, both are null
      if (anchor === null || head === null) {
        actionCells = [activeCell]
      } else {
        actionCells = notebook.widgets.slice(anchor, head + 1)
      }
      // console.log(`apply_on_cells with scope=${scope} on ${actionCells.length} cells`)
      actionCells.forEach(to_apply)
}

but it does not always work, and in some cases I get this error

How should I write the code to iterate over all the selected cells ?

(there seems to be an underlying assumption that the active cell is always the first of the selected cells; but there are very common moves that break this assumption: use Command-A to select all cells; or use shift-down arrow to select more cells going down, etc…)

thanks !