The Now Platform® Washington DC release is live. Watch now!
You may sometimes find yourself writing code over and over again with only minor variations. The pattern of these blocks of code (often a function) is the same, but some small particulars may vary. The brute-force approach is to simply bite the bullet and write separate functions to handle each variation, as in this (unreasonably) simple example where we write functions to return particular powers of a number:
gs.log('The square of 5 is: ' + square(5));
gs.log('The cube of 5 is: ' + cube(5));
function square(n) {
return Math.pow(n, 2);
}
function cube(n) {
return Math.pow(n, 3);
}
var square = makePowerFunction(2);
var cube = makePowerFunction(3);
gs.log('The square of 5 is: ' + square(5));
gs.log('The cube of 5 is: ' + cube(5));
function makePowerFunction(exp) {
var e = exp;
return pow;
function pow(n) {
return Math.pow(n, e);
}
}
var queryUser = queryFactory('sys_user', 'name');
var queryComputer = queryFactory('cmdb_ci_computer', 'name');
var x = queryUser('SlightlyLoony');
gs.log('Have user SlightlyLoony: ' + x.next());
var y = queryComputer('sandb01');
if (y.next())
gs.log('Computer sandb01 is at IP: ' + y.ip_address);
function queryFactory(table, field) {
var t = table;
var f = field;
return query;
function query(value) {
var gr = new GlideRecord(t);
gr.addQuery(f, value);
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.