1
0
mirror of https://github.com/stedolan/jq.git synced 2024-05-11 05:55:39 +00:00

Add floor operator

This commit is contained in:
Nicolas Williams
2013-06-17 20:50:45 -05:00
parent 1d839ff9df
commit 7c4171d414
3 changed files with 17 additions and 0 deletions

View File

@@ -44,6 +44,7 @@ version.h: .remake-version-h
bin_PROGRAMS = jq bin_PROGRAMS = jq
jq_SOURCES = ${JQ_SRC} main.c jq_SOURCES = ${JQ_SRC} main.c
jq_LDADD = -lm
### Tests (make check) ### Tests (make check)

View File

@@ -1,3 +1,4 @@
#include <math.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "builtin.h" #include "builtin.h"
@@ -66,6 +67,15 @@ static jv f_plus(jv input, jv a, jv b) {
} }
} }
static jv f_floor(jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "cannot be floored");
}
jv ret = jv_number(floor(jv_number_value(input)));
jv_free(input);
return ret;
}
static jv f_negate(jv input) { static jv f_negate(jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) { if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "cannot be negated"); return type_error(input, "cannot be negated");
@@ -480,6 +490,7 @@ static jv f_error(jv input, jv msg) {
} }
static const struct cfunction function_list[] = { static const struct cfunction function_list[] = {
{(cfunction_ptr)f_floor, "_floor", 1},
{(cfunction_ptr)f_plus, "_plus", 3}, {(cfunction_ptr)f_plus, "_plus", 3},
{(cfunction_ptr)f_negate, "_negate", 1}, {(cfunction_ptr)f_negate, "_negate", 1},
{(cfunction_ptr)f_minus, "_minus", 3}, {(cfunction_ptr)f_minus, "_minus", 3},
@@ -564,6 +575,7 @@ static const char* const jq_builtins[] = {
"def unique: group_by(.) | map(.[0]);", "def unique: group_by(.) | map(.[0]);",
"def max_by(f): _max_by_impl(map([f]));", "def max_by(f): _max_by_impl(map([f]));",
"def min_by(f): _min_by_impl(map([f]));", "def min_by(f): _min_by_impl(map([f]));",
"def floor: _floor;",
"def add: reduce .[] as $x (null; . + $x);", "def add: reduce .[] as $x (null; . + $x);",
"def del(f): delpaths([path(f)]);", "def del(f): delpaths([path(f)]);",
"def _assign(paths; value): value as $v | reduce path(paths) as $p (.; setpath($p; $v));", "def _assign(paths; value): value as $v | reduce path(paths) as $p (.; setpath($p; $v));",

View File

@@ -362,6 +362,10 @@ null
[5,6] [5,6]
[1,2,3] [1,2,3]
[.[]|floor]
[-1.1,1.1,1.9]
[-2, 1, 1]
def f(x): x | x; f([.], . + [42]) def f(x): x | x; f([.], . + [42])
[1,2,3] [1,2,3]
[[[1,2,3]]] [[[1,2,3]]]