MCPcopy Create free account
hub / github.com/Effect-TS/effect / matchingBlocks

Function matchingBlocks

packages/effect/src/TextDiff.ts:795–922  ·  view source on GitHub ↗
(
  n: number,
  m: number,
  equals: (i: number, j: number) => boolean,
  maxEdits = Infinity
)

Source from the content-addressed store, hash-verified

793 * when the search cap is exceeded.
794 */
795const matchingBlocks = (
796 n: number,
797 m: number,
798 equals: (i: number, j: number) => boolean,
799 maxEdits = Infinity
800): Array<Block> => {
801 const blocks: Array<Block> = []
802 const push = (a: number, b: number, length: number) => {
803 if (length === 0) return
804 const last = blocks[blocks.length - 1]
805 if (last !== undefined && last.a + last.length === a && last.b + last.length === b) {
806 blocks[blocks.length - 1] = { a: last.a, b: last.b, length: last.length + length }
807 } else {
808 blocks.push({ a, b, length })
809 }
810 }
811
812 // Forward and reverse furthest-reaching x per diagonal, offset by n + m + 1
813 const offset = n + m + 1
814 const vf = new Int32Array(2 * offset + 1)
815 const vb = new Int32Array(2 * offset + 1)
816 // The searches meet after half the edits of a region, so a region needing at
817 // most `maxEdits` edits is solved within `maxD` steps of each search
818 const maxD = Math.ceil(Math.max(0, maxEdits) / 2)
819
820 // Returns the middle snake of a minimal path in absolute coordinates, or an
821 // empty snake at the furthest point reached when the region needs more than
822 // `maxEdits` edits, or undefined when no point inside the region was reached
823 const findSplit = (aLo: number, aHi: number, bLo: number, bHi: number): Snake | undefined => {
824 const N = aHi - aLo
825 const M = bHi - bLo
826 const delta = N - M
827 const odd = (delta & 1) === 1
828 const limit = Math.min((N + M + 1) >> 1, maxD)
829 vf[offset + 1] = 0
830 vb[offset + 1] = 0
831 for (let d = 0; d <= limit; d++) {
832 for (let k = -d; k <= d; k += 2) {
833 let x = k === -d || (k !== d && vf[offset + k - 1] < vf[offset + k + 1])
834 ? vf[offset + k + 1]
835 : vf[offset + k - 1] + 1
836 let y = x - k
837 const x0 = x
838 const y0 = y
839 while (x < N && y < M && equals(aLo + x, bLo + y)) {
840 x++
841 y++
842 }
843 vf[offset + k] = x
844 if (odd && k >= delta - (d - 1) && k <= delta + (d - 1) && x + vb[offset + delta - k] >= N) {
845 return { x: aLo + x0, y: bLo + y0, u: aLo + x, v: bLo + y }
846 }
847 }
848 for (let k = -d; k <= d; k += 2) {
849 let x = k === -d || (k !== d && vb[offset + k - 1] < vb[offset + k + 1])
850 ? vb[offset + k + 1]
851 : vb[offset + k - 1] + 1
852 let y = x - k

Callers 1

editScriptFunction · 0.85

Calls 4

findSplitFunction · 0.85
pushFunction · 0.70
equalsFunction · 0.70
pushMethod · 0.65

Tested by

no test coverage detected