Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Last active May 27, 2016 20:23
Show Gist options
  • Save jmakeig/6898dfa2af428a230101f21b60fd047e to your computer and use it in GitHub Desktop.
Save jmakeig/6898dfa2af428a230101f21b60fd047e to your computer and use it in GitHub Desktop.
Extending MarkLogic Sequences with Array methods
'use strict';
/**
* @param {number} begin Zero-based index to start
* @param {number} [end] Zero-based index to end. Does not support negative indexes, like `Array.prototype.slice`
* @return {Sequence}
*/
Sequence.prototype.slice = function(begin, end) {
if('number' !== typeof begin) { throw new TypeError('begin must be a number'); }
if(end) {
return fn.subsequence(this, begin + 1, end - begin + 1);
}
return fn.subsequence(this, begin + 1);
}
/**
* Execute a function on each item.
*
* @param {function} fct
* @param {object} [that]
* @return {Iterator}
*/
Sequence.prototype.map = function*(fct, that) {
if('function' !== typeof fct) { throw new TypeError('fct must be a function'); }
for(let item of this) {
yield fct.call(that || null, item);
}
}
/**
* Lazily evaluate XPath over each item.
*
* @param {string} path
* @param {object} [bindings]
* @param {object} [that]
* @return {Iterator}
*/
Sequence.prototype.xpath = function*(path, bindings, that) {
if(null === path || 'undefined' === typeof path) { throw new TypeError('path must be a string of XPath'); }
for(let item of this) {
if(item instanceof Node || item instanceof Document || 'function' === typeof item.xpath) {
yield* item.xpath(path, bindings);
}
}
}
/**
*
* @callback reducer
* @param {object} value The previous value
* @param {object} item The current item
* @param {number} index The index of the current item
* @param {Sequence} sequence The parent `Sequence`
* @return {object} The next value
*/
/**
* Accumulate a value over each item.
*
* @param {reducer} fct
* @param {object} init Initial value
*/
Sequence.prototype.reduce = function(fct, init) {
let value = init, index = 0;
for(let item of this) {
value = fct.call(null, value, item, index++, this);
}
return value;
}
const seq = Sequence.from(
[
xdmp.unquote('<foo><bar/></foo>'),
xdmp.unquote('<foo><bar/></foo>'),
xdmp.unquote('<foo><baz/></foo>')
]
);
Sequence.from(
seq.xpath('//bar')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment