Skip to content

Instantly share code, notes, and snippets.

@damonfeldman
Created September 2, 2021 19:34
Show Gist options
  • Save damonfeldman/6ad15edf650c6f92676c8749e47fd48d to your computer and use it in GitHub Desktop.
Save damonfeldman/6ad15edf650c6f92676c8749e47fd48d to your computer and use it in GitHub Desktop.
Handy method to log or print information about objects while using marklogic
// helper function to get all method names including prototype inherited
function getMethods(obj) {
let ms = getMethodsDups(obj)
let uniq = ms.filter(
(item, pos, self) => {
return self.indexOf(item) == pos;
}
)
return uniq
}
function getMethodsDups(obj) {
let myFunctions = Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')
let p = Object.getPrototypeOf(obj)
return p ? myFunctions.concat(getMethodsDups(p)) : myFunctions
}
// describe an object or value and differentiate various important MarkLogic objects that log or render the same
function describe(x) {
if (["string", "number", "boolean"].includes(typeof x))
return typeof x
if (Array.isArray(x)) {
if (x.length == 0)
return "Array (empty)"
else
return "Array(item[0]: "+describe(x[0])+")"
}
let methods = getMethods(x)
if (methods.includes("toObject") && methods.includes("toJSON") && x.nodeKind ) {
return "Node: " + x.nodeKind
}
else if (methods.length==11 && methods.includes("hasOwnProperty"))
return "Regular Object" // regular JS object has 11 methods (note: so does a boolean)
else if (methods.length==14 && methods.includes("toArray") && methods.includes("toJSON")) {
if (fn.count(x)==0)
return "Sequence (empty)"
else {
let h = fn.head(x)
return "Sequence(item 1: "+describe(fn.head(x))+ ")" // MarkLogic object representing an XPath sequence type
}
}
else if (typeof x == "boolean")
return "xx"
}
// TEST ////
let c = {foo: "foooo", bars: [{bar1:"b1"}, {bar2:2}, "b3"]}
const builder = new NodeBuilder()
builder.startDocument()
builder.addNode(c) // maybe the map of sequences is converted when added as a node
builder.endDocument()
var newDocument = builder.toNode()
let f = newDocument.xpath("/foo")
let bs = newDocument.xpath("/bars")
let s = new Sequence([true, 2, "apple"])
let m = xdmp.xqueryEval("let $m := map:map() let $_ := map:put($m, 'foo', 'foooo') return $m")
result = [
describe("apple"),
describe(["apple"]),
describe(1),
describe(false),
describe(newDocument),
describe(s),
describe(m),
describe(c),
describe(f),
describe(bs),
]
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment