Skip to content

Commit a86c036

Browse files
committed
Reimplement split/1 intrinsic
1 parent f0af207 commit a86c036

3 files changed

Lines changed: 28 additions & 4 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ Note that the tests are meant to be used with jq 1.7.
166166
- [x] `select(f)`
167167
- [x] `setpath` (passthrough)
168168
- [x] `sort`, `sort_by(f)`
169-
- [ ] `split($s)`
169+
- [x] `split($s)`
170170
- [x] `split($re; flags)`
171171
- [x] `splits($re)`, `splits($re; flags)`
172172
- [x] `startswith($s)`

jqjq.jq

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1924,6 +1924,9 @@ def scalars: select(_is_scalar);
19241924
19251925
def add: reduce .[] as $v (null; . + $v);
19261926
1927+
def startswith($s): .[0:$s | length] == $s;
1928+
def endswith($s): .[$s | -length:] == $s;
1929+
19271930
def _nwise($n):
19281931
def n:
19291932
if length <= $n then .
@@ -1940,6 +1943,22 @@ def splits($re; flags):
19401943
def splits($re): splits($re; null);
19411944
def split($re; flags): [splits($re; flags)];
19421945
1946+
def _strsplit($delim; $acc):
1947+
if . == \"\" then $acc
1948+
elif startswith($delim) then
1949+
$acc, (.[$delim | length:] | _strsplit($delim; \"\"))
1950+
else .[:1] as $c | .[1:] | _strsplit($delim; $acc + $c)
1951+
end;
1952+
def _strsplit0:
1953+
if . == \"\" then empty else .[:1], (.[1:] | _strsplit0) end;
1954+
def split($s):
1955+
if type != \"string\" or ($s | type != \"string\") then
1956+
error(\"split input and separator must be strings\")
1957+
elif . == \"\" then []
1958+
elif $s == \"\" then [_strsplit0]
1959+
else [_strsplit($s; \"\")]
1960+
end;
1961+
19431962
def join($s):
19441963
if length == 0 then \"\"
19451964
else
@@ -2103,9 +2122,6 @@ def nth($n): .[$n];
21032122
21042123
def isempty(f): [limit(1; f)] == [];
21052124
2106-
def startswith($s): .[0:$s | length] == $s;
2107-
def endswith($s): .[$s | -length:] == $s;
2108-
21092125
def _strindices($i):
21102126
. as $s | [range(length) | select($s[.:] | startswith($i))];
21112127
def indices($i):

jqjq.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -979,6 +979,14 @@ null
979979
"a,b|c,d,e||f,g,h,|,|,i,j"
980980
[1,3,22,19,[1,5,7,12,14,16,18,20,22],[3,9,10,17,19]]
981981

982+
[.[] | split(", ")]
983+
["", "a,b, c, d, e,f", ", a,b, c, d, e,f, "]
984+
[[],["a,b","c","d","e,f"],["","a,b","c","d","e,f",""]]
985+
986+
[.[] | split("")]
987+
["", "abc"]
988+
[[],["a","b","c"]]
989+
982990
# SKIP_JQ
983991
# test below does not work with standard jq because of missing features or bugs
984992

0 commit comments

Comments
 (0)