PHP's xdiff_string_patch in JavaScript

Here’s what our current JavaScript equivalent to PHP's xdiff_string_patch looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
module.exports = function xdiff_string_patch (originalStr, patch, flags, errorObj) { // eslint-disable-line camelcase
// discuss at: http://locutus.io/php/xdiff_string_patch/
// original by: Brett Zamir (http://brett-zamir.me)
// improved by: Steven Levithan (stevenlevithan.com)
// note 1: The XDIFF_PATCH_IGNORESPACE flag and the error argument are not
// note 1: currently supported.
// note 2: This has not been tested exhaustively yet.
// note 3: The errorObj parameter (optional) if used must be passed in as a
// note 3: object. The errors will then be written by reference into it's `value` property
// example 1: xdiff_string_patch('', '@@ -0,0 +1,1 @@\n+Hello world!')
// returns 1: 'Hello world!'

// First two functions were adapted from Steven Levithan, also under an MIT license
// Adapted from XRegExp 1.5.0
// (c) 2007-2010 Steven Levithan
// MIT License
// <http://xregexp.com>

var _getNativeFlags = function (regex) {
// Proposed for ES4; included in AS3
return [
(regex.global ? 'g' : ''),
(regex.ignoreCase ? 'i' : ''),
(regex.multiline ? 'm' : ''),
(regex.extended ? 'x' : ''),
(regex.sticky ? 'y' : '')
].join('')
}

var _cbSplit = function (string, sep) {
// If separator `s` is not a regex, use the native `split`
if (!(sep instanceof RegExp)) {
// Had problems to get it to work here using prototype test
return String.prototype.split.apply(string, arguments)
}
var str = String(string)
var output = []
var lastLastIndex = 0
var match
var lastLength
var limit = Infinity
var x = sep._xregexp
// This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero
// and restore it to its original value when we're done using the regex
// Brett paring down
var s = new RegExp(sep.source, _getNativeFlags(sep) + 'g')
if (x) {
s._xregexp = {
source: x.source,
captureNames: x.captureNames ? x.captureNames.slice(0) : null
}
}

while ((match = s.exec(str))) {
// Run the altered `exec` (required for `lastIndex` fix, etc.)
if (s.lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index))

if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1))
}

lastLength = match[0].length
lastLastIndex = s.lastIndex

if (output.length >= limit) {
break
}
}

if (s.lastIndex === match.index) {
s.lastIndex++
}
}

if (lastLastIndex === str.length) {
if (!s.test('') || lastLength) {
output.push('')
}
} else {
output.push(str.slice(lastLastIndex))
}

return output.length > limit ? output.slice(0, limit) : output
}

var i = 0
var ll = 0
var ranges = []
var lastLinePos = 0
var firstChar = ''
var rangeExp = /^@@\s+-(\d+),(\d+)\s+\+(\d+),(\d+)\s+@@$/
var lineBreaks = /\r?\n/
var lines = _cbSplit(patch.replace(/(\r?\n)+$/, ''), lineBreaks)
var origLines = _cbSplit(originalStr, lineBreaks)
var newStrArr = []
var linePos = 0
var errors = ''
var optTemp = 0 // Both string & integer (constant) input is allowed
var OPTS = {
// Unsure of actual PHP values, so better to rely on string
'XDIFF_PATCH_NORMAL': 1,
'XDIFF_PATCH_REVERSE': 2,
'XDIFF_PATCH_IGNORESPACE': 4
}

// Input defaulting & sanitation
if (typeof originalStr !== 'string' || !patch) {
return false
}
if (!flags) {
flags = 'XDIFF_PATCH_NORMAL'
}

if (typeof flags !== 'number') {
// Allow for a single string or an array of string flags
flags = [].concat(flags)
for (i = 0; i < flags.length; i++) {
// Resolve string input to bitwise e.g. 'XDIFF_PATCH_NORMAL' becomes 1
if (OPTS[flags[i]]) {
optTemp = optTemp | OPTS[flags[i]]
}
}
flags = optTemp
}

if (flags & OPTS.XDIFF_PATCH_NORMAL) {
for (i = 0, ll = lines.length; i < ll; i++) {
ranges = lines[i].match(rangeExp)
if (ranges) {
lastLinePos = linePos
linePos = ranges[1] - 1
while (lastLinePos < linePos) {
newStrArr[newStrArr.length] = origLines[lastLinePos++]
}
while (lines[++i] && (rangeExp.exec(lines[i])) === null) {
firstChar = lines[i].charAt(0)
switch (firstChar) {
case '-':
// Skip including that line
++linePos
break
case '+':
newStrArr[newStrArr.length] = lines[i].slice(1)
break
case ' ':
newStrArr[newStrArr.length] = origLines[linePos++]
break
default:
// Reconcile with returning errrors arg?
throw new Error('Unrecognized initial character in unidiff line')
}
}
if (lines[i]) {
i--
}
}
}
while (linePos > 0 && linePos < origLines.length) {
newStrArr[newStrArr.length] = origLines[linePos++]
}
} else if (flags & OPTS.XDIFF_PATCH_REVERSE) {
// Only differs from above by a few lines
for (i = 0, ll = lines.length; i < ll; i++) {
ranges = lines[i].match(rangeExp)
if (ranges) {
lastLinePos = linePos
linePos = ranges[3] - 1
while (lastLinePos < linePos) {
newStrArr[newStrArr.length] = origLines[lastLinePos++]
}
while (lines[++i] && (rangeExp.exec(lines[i])) === null) {
firstChar = lines[i].charAt(0)
switch (firstChar) {
case '-':
newStrArr[newStrArr.length] = lines[i].slice(1)
break
case '+':
// Skip including that line
++linePos
break
case ' ':
newStrArr[newStrArr.length] = origLines[linePos++]
break
default:
// Reconcile with returning errrors arg?
throw new Error('Unrecognized initial character in unidiff line')
}
}
if (lines[i]) {
i--
}
}
}
while (linePos > 0 && linePos < origLines.length) {
newStrArr[newStrArr.length] = origLines[linePos++]
}
}

if (errorObj) {
errorObj.value = errors
}

return newStrArr.join('\n')
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/xdiff/xdiff_string_patch'). You could also require the xdiff module in full so that you could access xdiff.xdiff_string_patch instead.

If you intend to target the browser, you can then use a module bundler such as Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Notes

  • The XDIFF_PATCH_IGNORESPACE flag and the error argument are not currently supported.

  • This has not been tested exhaustively yet.

  • The errorObj parameter (optional) if used must be passed in as a object. The errors will then be written by reference into it’s value property

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1xdiff_string_patch('', '@@ -0,0 +1,1 @@\n+Hello world!')'Hello world!'

« More PHP xdiff functions