The Now Platform® Washington DC release is live. Watch now!
Have you ever written a handy-dandy little script function, and then wished you could have it accept different kinds of arguments? For instance, perhaps you wrote a function that took a list of people's first and last names (in an array of two-element arrays) that figured out how many characters were in the longest combinations. Cool! Then you realize that you could make that function even more generally useful if it could also accept a GlideRecord with first and last name fields. But is it really possible to make a single function that could accept either form of argument?
Why, yes it is!
Consider this test code:
gs.log('Method 1: string argument');
var nicGR = new GlideRecord('cmdb_ci_network_adapter');
nicGR.addQuery('ip_address', '10.10.10.135');
nicGR.query();
if (nicGR.next()) {
var cis = getCIs(nicGR.cmdb_ci);
while (cis.next())
gs.log(' ' + cis.name);
}
gs.log('Method 2: GlideRecord argument');
var nicGR = new GlideRecord('cmdb_ci_network_adapter');
nicGR.addQuery('ip_address', '10.10.10.135');
nicGR.query();
var cis = getCIs(nicGR, 'cmdb_ci');
while (cis.next())
gs.log(' ' + cis.name);
gs.log('Method 3: Array of sys_ids argument');
var sysIDs = [];
sysIDs.push('d48740560a0a3c19009fcd0945f91624');
var cis = getCIs(sysIDs);
while (cis.next())
gs.log(' ' + cis.name);
gs.log('Method 4: function argument');
var cis = getCIs(getNICs, 'cmdb_ci');
while (cis.next())
gs.log(' ' + cis.name);
function getNICs() {
var nicGR = new GlideRecord('cmdb_ci_network_adapter');
nicGR.addQuery('ip_address', '10.10.10.135');
nicGR.query();
return nicGR;
}
Method 1: string argument
sanops05
Method 2: GlideRecord argument
sanops05
Method 3: Array of sys_ids argument
sanops05
Method 4: function argument
sanops05
function getCIs(source, field) {
// get ourselves a list of CI sys_id values...
if (typeof source == 'function')
source = source();
var sysIDs = [];
if (source instanceof GlideRecord) {
if (!field)
return null;
while (source.next())
sysIDs.push('' + source.getValue(field));
} else if (source instanceof Array)
sysIDs = source;
else
sysIDs.push('' + source);
// now we'll do the actual work, with an array of sys_ids...
var gr = new GlideRecord('cmdb_ci');
gr.addQuery('sys_id', sysIDs);
gr.query();
return gr;
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.