From 4bcff408280afe1072f771c2330dbf0da7d0fbb8 Mon Sep 17 00:00:00 2001 From: Nicolas Williams Date: Mon, 7 Jul 2014 22:25:34 -0500 Subject: [PATCH] Make `any/2` and `all/2` efficient using `foreach` --- builtin.c | 14 ++++++++++++-- tests/all.test | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/builtin.c b/builtin.c index 38ad1cfc..4febe8fa 100644 --- a/builtin.c +++ b/builtin.c @@ -936,9 +936,19 @@ static const char* const jq_builtins[] = { "def any: reduce .[] as $i (false; . or $i);", "def all: reduce .[] as $i (true; . and $i);", "def any(condition): reduce .[] as $i (false; . or ($i|condition));", + "def any(generator; condition):" + " [false," + " foreach generator as $i" + " (false;" + " if . then break elif $i | condition then true else . end;" + " if . then . else empty end)] | any;", "def all(condition): reduce .[] as $i (true; . and ($i|condition));", - "def any(generator; condition): reduce generator as $i (false; . or ($i|condition));", - "def all(generator; condition): reduce generator as $i (true; . and ($i|condition));", + "def all(generator; condition): " + " [true," + " foreach generator as $i" + " (true;" + " if .|not then break elif $i | condition then . else false end;" + " if .|not then . else empty end)]|all;", "def arrays: select(type == \"array\");", "def objects: select(type == \"object\");", "def iterables: arrays, objects;", diff --git a/tests/all.test b/tests/all.test index 1c8a3d3f..1175f1a6 100644 --- a/tests/all.test +++ b/tests/all.test @@ -502,6 +502,22 @@ reduce .[] as $x (0; . + $x) [1,2,4] 7 +. as $dot|any($dot[];not) +[1,2,3,4,true,false,1,2,3,4,5] +true + +. as $dot|any($dot[];not) +[1,2,3,4,true] +false + +. as $dot|all($dot[];.) +[1,2,3,4,true,false,1,2,3,4,5] +false + +. as $dot|all($dot[];.) +[1,2,3,4,true] +true + # # Paths #