Skip to content

Commit

Permalink
style: fixes from suggestions.
Browse files Browse the repository at this point in the history
Co-authored-by: itchyny <itchyny@cybozu.co.jp>
Signed-off-by: Eloy Coto <eloy.coto@acalustra.com>
  • Loading branch information
eloycoto and itchyny committed Feb 14, 2024
1 parent 949b647 commit 95cbcc5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 47 deletions.
68 changes: 22 additions & 46 deletions src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -784,54 +784,30 @@ static jv f_sort_by_impl(jq_state *jq, jv input, jv keys) {
/* (-1 - ix), where ix is the insertion point that would leave the array sorted. */
/* If the input is not sorted, bsearch will terminate but with irrelevant results. */
static jv f_bsearch(jq_state *jq, jv input, jv target) {
assert(jv_get_kind(input) == JV_KIND_ARRAY);
int len = jv_array_length(jv_copy(input));
if (len == 0) {
jv_free(input);
jv_free(target);
return jv_number(-1);
} else if (len == 1) {
int result = jv_cmp(target, jv_array_get(input, 0));
if (result == 0 ) {
return jv_number(0);
} else if (result > 0) {
return jv_number(-2);
} else {
return jv_number(-1);
}
}

int start = 0;
int end = len - 1;
jv answer = jv_null();
while (start <end) {
int mid = (start + end) / 2;
int result = jv_cmp(jv_copy(target), jv_array_get(jv_copy(input), mid));
if (result == 0) {
answer = jv_number(mid);
break;
} else if (start == end ) {
answer = jv_number(-1);
break;
} else if (result < 0 ) {
end = mid -1;
} else {
start = mid +1;
}
}
if (jv_get_kind(answer) == JV_KIND_NULL) {
int result = jv_cmp(target, jv_array_get(jv_copy(input), start));
if (result < 0) {
answer = jv_number(-1 - start);
}else {
answer = jv_number(-2 - start);
}
if (jv_get_kind(input) != JV_KIND_ARRAY) {
return type_error(input, "cannot be searched from");
}
int start = 0;
int end = jv_array_length(jv_copy(input));
jv answer = jv_invalid();
while (start < end) {
int mid = (start + end) / 2;
int result = jv_cmp(jv_copy(target), jv_array_get(jv_copy(input), mid));
if (result == 0) {
answer = jv_number(mid);
break;
} else if (result < 0) {
end = mid;
} else {
jv_free(target);
start = mid + 1;
}

jv_free(input);
return answer;
}
if (!jv_is_valid(answer)) {
answer = jv_number(-1 - start);
}
jv_free(input);
jv_free(target);
return answer;
}

static jv f_group_by_impl(jq_state *jq, jv input, jv keys) {
Expand Down
4 changes: 3 additions & 1 deletion tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -1547,10 +1547,12 @@ ascii_upcase
"useful but not for é"
"USEFUL BUT NOT FOR é"

bsearch(0,2,4)
bsearch(0,1,2,3,4)
[1,2,3]
-1
0
1
2
-4

bsearch({x:1})
Expand Down

0 comments on commit 95cbcc5

Please sign in to comment.