import "stringLib" as stringLib;

def debugLog($target; $value):
  if 
    ($ENV["JQ_DEBUG"] == $target)
    or
    ($target == "*")
    or
    ($ENV["JQ_DEBUG"] | split(",") | any(. as $debugTarget | $target | startswith($debugTarget | split("*")[0])))
   then
    debug({$target, $value})
  end;

def assert(cond; $msg): if cond then . else error($msg) end;
def assert($loc; cond; $msg): assert(cond; "\($loc.file):\($loc.line): " + $msg);

def firstN($n): .[:$n];

def orderedUnique:
  (reduce .[] as $value ([];
    if 
      (. | any(index($value)) | not)
    then . += [$value]
    else . end
  ));

def sortFilterFromString($filterString):
  ($filterString | split("|")).[] as $filter | 
    if 
      $filter == "reverse" then . | reverse
    elif ($filter | startswith("firstN")) then
      ($filter | ltrimstr("firstN(") | rtrimstr(")")) as $arg |
        . | firstN($arg | try fromjson catch error("invalid number passed to firstN"))
    end;