Hi Paul,
thanks for this snippet!
Have you already seen the built-in min/max functions?
max((1,2,3)), min((1,2,3))
Might save both, some bytes and milliseconds, neglectable but
nevertheless. :-)
Best from Konstanz
Michael
On 15 Aug 2014, at 22:02, Paul Swennenhuis wrote:
Hi all,
Triggered by a thread in this forum I decided to make a paged()
function that adds paging information to a node-set.
It does so by wrapping the node-set in an root element - with a name
of your choice - with attributes for total number of nodes,
start-index requested page-size, actual page-size and end-index.
The last function argument lets you select whether or not to output a
paged node-set or just wrap the node-set in a root element.
It's not very spectacular but it may be of use if you want to use
BaseX for paged results or endless scrolling.
Comments are appreciated.
The module with the paged() function:
-------------------------------------
module namespace lib = "My Library";
(:
lib:paged adds paging information to a node-set
in order to enable paged results for a web-app
Will return a node with the name as specified in $nodeName
along with total number of nodes ($total), start-index ($start),
requested page-size ($num), actual page-size ($displayed)
and end-index ($end) as attributes, followed by the subsequence of the
node-set
Collection MUST be a node-set (i.e. must NOT have a root element)
If $doPaged argument is false(), only the root node with the original
collection is returned
The parameter makes it easier to do a non-conditional call of the
function on a node-set
:)
declare function lib:paged ($collection, $nodeName, $start, $pageSize,
$doPaged) {
let $total := count($collection)
let $min := lib:max(lib:min($pageSize,lib:min($total,$total - $start +
1)),0)
return
element {$nodeName} {
if ($doPaged) then (
attribute total {$total},
attribute start {$start},
attribute pageSize {$pageSize},
attribute actualPageSize {$min},
attribute end {$start + $min - 1},
subsequence($collection, $start, $pageSize)
)
else
$collection
}
};
(: Return smallest of two numbers :)
declare function lib:min($a,$b) {
if ($a < $b) then $a else $b
};
(: Return largest of two numbers :)
declare function lib:max($a,$b) {
if ($a > $b) then $a else $b
};
------------------------------------
Usage example:
-----------------------------------
import module namespace lib="My Library" at "library.xqy";
lib:paged(collection("Facts")//city, 'cities', 500, 300, true())
------------------------------------
Paul