Created
April 18, 2019 21:05
-
-
Save haxiomic/fc02aab5c8276627cd1f6479fd0831da to your computer and use it in GitHub Desktop.
Split by character, but not inside scopes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scopePreservingSplit(str: String, by: String) { | |
var scopePairs = ['()', '[]', '{}', '<>']; | |
var scopeState = [0, 0, 0, 0]; | |
var parts = new Array<String>(); | |
var buffer = ''; | |
inline function handleScope(c) { | |
for (i in 0...scopePairs.length) { | |
var open = scopePairs[i].charAt(0); | |
var close = scopePairs[i].charAt(1); | |
if (c == open) { | |
scopeState[i]++; | |
break; | |
} | |
if (c == close) { | |
scopeState[i]--; | |
break; | |
} | |
} | |
} | |
for (i in 0...str.length) { | |
var c = str.charAt(i); | |
handleScope(c); | |
var withinScope = Lambda.find(scopeState, s -> s > 0) != null; | |
if (c == ',' && !withinScope) { | |
parts.push(buffer); | |
buffer = ''; | |
} else { | |
buffer += c; | |
} | |
} | |
parts.push(buffer); | |
return parts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment