Skip to content

Commit d6388d9

Browse files
authored
Merge pull request #299 from 01mf02/bsearch
Implement `bsearch`
2 parents bae8fba + 90f6efc commit d6388d9

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

jaq-json/src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,12 @@ fn base() -> Box<[Filter<RunPtr<Val>>]> {
395395
x.indices(&v).map(|idxs| idxs.map(to_int).collect())
396396
})
397397
}),
398+
("bsearch", v(1), |_, cv| {
399+
let to_idx = |r: Result<_, _>| r.map_or_else(|i| -1 - i as isize, |i| i as isize);
400+
unary(cv, move |a, x| {
401+
a.as_arr().map(|a| Val::Int(to_idx(a.binary_search(&x))))
402+
})
403+
}),
398404
])
399405
}
400406

@@ -502,6 +508,13 @@ impl Val {
502508
}
503509
}
504510

511+
fn as_arr(&self) -> Result<&Rc<Vec<Self>>, Error> {
512+
match self {
513+
Self::Arr(a) => Ok(a),
514+
_ => Err(Error::typ(self.clone(), Type::Arr.as_str())),
515+
}
516+
}
517+
505518
/// Try to parse a string to a [`Self::Float`], else return [`Self::Null`].
506519
fn from_dec_str(n: &str) -> Self {
507520
n.parse().map_or(Self::Null, Self::Float)

jaq-json/tests/funs.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ pub mod common;
55
use common::give;
66
use serde_json::json;
77

8+
yields!(bsearch_absent1, "[1, 3] | bsearch(0)", -1);
9+
yields!(bsearch_absent2, "[1, 3] | bsearch(2)", -2);
10+
yields!(bsearch_absent3, "[1, 3] | bsearch(4)", -3);
11+
yields!(bsearch_present, "[1, 3] | [bsearch(1, 3)]", [0, 1]);
12+
813
#[test]
914
fn has() {
1015
/* TODO: reenable these tests

0 commit comments

Comments
 (0)