Skip to content

Commit e4317a2

Browse files
committed
Merge pull request #54 from sharkdp/fix-regex-global-state
Reset Regex state after calling 'test', resolves #7
2 parents 5772cb6 + 26941a9 commit e4317a2

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

src/Data/String/Regex.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ exports.flags = function (r) {
3737

3838
exports.test = function (r) {
3939
return function (s) {
40-
return r.test(s);
40+
var lastIndex = r.lastIndex;
41+
var result = r.test(s);
42+
r.lastIndex = lastIndex;
43+
return result;
4144
};
4245
};
4346

src/Data/String/Regex.purs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,9 @@ parseFlags s =
8484
, unicode: contains "u" s
8585
}
8686

87-
-- | Returns `true` if the `Regex` matches the string.
87+
-- | Returns `true` if the `Regex` matches the string. In contrast to
88+
-- | `RegExp.prototype.test()` in JavaScript, `test` does not affect
89+
-- | the `lastIndex` property of the Regex.
8890
foreign import test :: Regex -> String -> Boolean
8991

9092
foreign import _match :: (forall r. r -> Maybe r)

test/Test/Data/String/Regex.purs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,10 @@ testStringRegex = do
3636
assert $ split (regex' "" noFlags) "abc" == ["a", "b", "c"]
3737
assert $ split (regex' "b" noFlags) "" == [""]
3838
assert $ split (regex' "b" noFlags) "abc" == ["a", "c"]
39+
40+
log "test"
41+
-- Ensure that we have referential transparency for calls to 'test'. No
42+
-- global state should be maintained between these two calls:
43+
let pattern = regex' "a" (parseFlags "g")
44+
assert $ test pattern "a"
45+
assert $ test pattern "a"

0 commit comments

Comments
 (0)