Skip to content

Commit

Permalink
Implement indices, index and rindex.
Browse files Browse the repository at this point in the history
  • Loading branch information
kklingenberg committed Feb 4, 2024
1 parent ce988d5 commit db10edc
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions jaq-std/src/std.jq
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,28 @@ def any: any(.[]; .);
def in(xs) : . as $x | xs | has ($x);
def inside(xs): . as $x | xs | contains($x);

# Indexing
def indices($i):
def enumerate:
. as $thing |
if type == "string"
then range(length) | [., $thing[.:.+1]]
else range(length) | [., $thing[.]]
end;

def windowed($size):
if $size <= 0 then empty
else . as $array | range(length - $size + 1) | $array[.:. + $size]
end;

if ($i | type) == "array" or (type == "string" and ($i | type) == "string")
then [[windowed($i | length)] | enumerate | select(.[1] == $i)[0]]
else [enumerate | select(.[1] == $i)[0]]
end;

def index($i): indices($i) | .[0];
def rindex($i): indices($i) | .[-1:][0];

# Walking
def walk(f): def rec: (.[]? |= rec) | f; rec;

Expand Down
21 changes: 21 additions & 0 deletions jaq-std/tests/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,27 @@ yields!(flatten_obj, "{a: 1} | flatten", json!([{"a": 1}]));
// jq gives an error here
yields!(flatten_num, "0 | flatten", [0]);

#[test]
fn indices() {
give(
json!("a,b, cd, efg, hijk"),
r#"indices(", ")"#,
json!([3, 7, 12]),
);
give(json!([0, 1, 2, 1, 3, 1, 4]), "indices(1)", json!([1, 3, 5]));
give(
json!([0, 1, 2, 3, 1, 4, 2, 5, 1, 2, 6, 7]),
"indices([1, 2])",
json!([1, 8]),
);
give(json!([]), "indices([])", json!([]));
give(json!([1, 2]), "indices([1, 2, 3])", json!([]));
give(json!(["a", "b", "c"]), r#"indices("b")"#, json!([1]));
give(json!([0, 0, 0]), "indices([0, 0])", json!([0, 1]));
// This is a discrepancy with jq: jq simply gives [0] and doesn't report the second match
give(json!("aaa"), r#"indices("aa")"#, json!([0, 1]));
}

#[test]
fn inside() {
give(
Expand Down

0 comments on commit db10edc

Please sign in to comment.