Binds a function to a specific object.
Binds a function to a specific object.
Name | Type | Description |
---|---|---|
me | Object | The object to bind to. |
fn | Function | The function to bind. |
The bound function.
var obj = {a: 1, b: function() { console.log(a); }};
var bound = splunkjs.Utils.bind(obj, obj.b);
bound(); // prints 1
root.bind = function(me, fn) {
return function() {
return fn.apply(me, arguments);
};
};
Creates a shallow-cloned copy of an object or array.
Name | Type | Description |
---|---|---|
obj | Object,Array | The object or array to clone. |
The cloned object or array.
function() {
console.log(splunkjs.Utils.clone({foo: "bar"})); // {foo: "bar"}
console.log(splunkjs.Utils.clone([1,2,3])); // [1,2,3]
}
root.clone = function(obj) {
if (!root.isObject(obj)) {
return obj;
}
return root.isArray(obj) ? obj.slice() : root.extend({}, obj);
};
Indicates whether an array contains a specific object.
Name | Type | Description |
---|---|---|
arr | Array | The array to search in. |
obj | Anything | The object to search for. |
true
if the array contains the object, false
if not.
var a = {a: 3};
var b = [{}, {c: 1}, {b: 1}, a];
var contained = splunkjs.Utils.contains(b, a); // true
root.contains = function(arr, obj) {
arr = arr || [];
return (root.indexOf(arr, obj) >= 0);
};
Indicates whether a string ends with a specific suffix.
Name | Type | Description |
---|---|---|
original | String | The string to search in. |
suffix | String | The suffix to search for. |
true
if the string ends with the suffix, false
if not.
var ends = splunkjs.Utils.endsWith("foo-splunk", "-splunk");
root.endsWith = function(original, suffix) {
let matches = original.match(suffix + "$");
return matches && matches.length > 0 && matches[0] === suffix;
};
var toString = Object.prototype.toString;
Extends a given object with all the properties from other source objects.
Name | Type | Description |
---|---|---|
obj | Object | The object to extend. |
sources | Object... | The source objects from which to take properties. |
The extended object.
function() {
console.log(splunkjs.Utils.extend({foo: "bar"}, {a: 2})); // {foo: "bar", a: 2}
}
root.extend = function(obj) {
root.forEach(Array.prototype.slice.call(arguments, 1), function(source) {
for (let prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
Applies an iterator function to each element in an object.
Name | Type | Description |
---|---|---|
obj | Object,Array | An object or array. |
iterator | Function | The function to apply to each element: |
context | Object | A context to apply to the function (optional). |
splunkjs.Utils.forEach([1,2,3], function(el) { console.log(el); }); // 1,2,3
root.forEach = function(obj, iterator, context) {
if (obj === null) {
return;
}
if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
obj.forEach(iterator, context);
}
else if (obj.length === +obj.length) {
for (let i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return;
}
}
}
else {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return;
}
}
}
}
};
Finds a version in a dictionary.
Name | Type | Description |
---|---|---|
version | String | The version to search for. |
map | Object | The dictionary to search. |
The value of the dictionary at the closest version match.
root.getWithVersion = function(version, map) {
map = map || {};
let currentVersion = (version + "") || "";
while (currentVersion !== "") {
if (map.hasOwnProperty(currentVersion)) {
return map[currentVersion];
}
else {
currentVersion = currentVersion.slice(
0,
currentVersion.lastIndexOf(".")
);
}
}
return map["default"];
};
Searches an array for a specific object and returns its location.
Name | Type | Description |
---|---|---|
arr | Array | The array to search in. |
search | Anything | The object to search for. |
The index of the object (search
), or -1
if the object wasn't found.
var a = ["a", "b', "c"];
console.log(splunkjs.Utils.indexOf(a, "b")) //== 1
console.log(splunkjs.Utils.indexOf(a, "d")) //== -1
root.indexOf = function(arr, search) {
for(let i=0; i<arr.length; i++) {
if (arr[i] === search) {
return i;
}
}
return -1;
};
Indicates whether an argument is an array.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is an array, false
if not.
function() {
console.log(splunkjs.Utils.isArray(arguments)); // false
console.log(splunkjs.Utils.isArray([1,2,3])); // true
}
root.isArray = Array.isArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
Indicates whether an argument is empty.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is empty, false
if not.
function() {
console.log(splunkjs.Utils.isEmpty({})); // true
console.log(splunkjs.Utils.isEmpty({a: 1})); // false
}
root.isEmpty = function(obj) {
if (root.isArray(obj) || root.isString(obj)) {
return obj.length === 0;
}
for (let key in obj) {
if (this.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
};
Indicates whether an argument is a function.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is a function, false
if not.
function() {
console.log(splunkjs.Utils.isFunction([1,2,3]); // false
console.log(splunkjs.Utils.isFunction(function() {})); // true
}
root.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
Indicates whether an argument is a number.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is a number, false
if not.
function() {
console.log(splunkjs.Utils.isNumber(1); // true
console.log(splunkjs.Utils.isNumber(function() {})); // false
}
root.isNumber = function(obj) {
return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
};
Indicates whether an argument is an object.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is an object, false
if not.
function() {
console.log(splunkjs.Utils.isObject({abc: "abc"}); // true
console.log(splunkjs.Utils.isObject("abc"); // false
}
root.isObject = function(obj) {
Indicates whether an argument is a string.
Name | Type | Description |
---|---|---|
obj | Anything | The argument to evaluate. |
true
if the argument is a string, false
if not.
function() {
console.log(splunkjs.Utils.isString("abc"); // true
console.log(splunkjs.Utils.isString(function() {})); // false
}
root.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
Tests whether a value appears in a given object.
Name | Type | Description |
---|---|---|
val | Anything | The value to search for. |
obj | Object | The object to search in. |
root.keyOf = function(val, obj) {
for (let k in obj) {
if (obj.hasOwnProperty(k) && obj[k] === val) {
return k;
}
}
return undefined;
};
Extracts namespace information from a dictionary of properties. Namespace information includes values for owner, app, and sharing.
Name | Type | Description |
---|---|---|
props | Object | The dictionary of properties. |
Namespace information from the properties dictionary.
root.namespaceFromProperties = function(props) {
if (root.isUndefined(props) || root.isUndefined(props.acl)) {
return {
owner: '',
app: '',
sharing: ''
};
}
return {
owner: props.acl.owner,
app: props.acl.app,
sharing: props.acl.sharing
};
};
Runs multiple functions (tasks) in parallel. Each task takes the function as a parameter. When all tasks have been completed or if an error occurs, the function returns a combined results of all tasks.
Note: Tasks might not be run in the same order as they appear in the array, but the results will be returned in that order.
Name | Type | Description |
---|---|---|
tasks | Function | An array of functions. |
fromMap | Boolean | set to true when method call is made from parallerMap function. (optional) |
let [err, one, two] = await Utils.parallel([
function() {
return [null, 1];
},
function() {
return [null, 2, 3];
}]
);
console.log(err); // == null
console.log(one); // == 1
console.log(two); // == [1,2]
root.parallel = async function (tasks, fromMap) {
let res = [];
if(!root.isArray(tasks) && root.isFunction(fromMap)){
let taskList = [];
Object.keys(arguments).forEach(key => {
taskList.push(arguments[key]);
});
tasks = taskList;
fromMap = false;
}
for(let task of tasks) {
let result = task();
res.push(result);
}
let result = await Promise.all(res);
let response = [];
for(let resp of result){
if(resp){
if(resp[0]){
return [resp[0], null];
}
if(resp.length > 2){
response.push(resp.slice(1));
}else{
response.push(resp[1]);
}
}
}
return fromMap ? [null, response] : [null, ...response];
}
Applies an asynchronous function over each element in an array, in parallel. If an error occurs, the function returns an error.
Name | Type | Description |
---|---|---|
vals | Array | An array of values. |
fn | Function | A function (possibly asynchronous) to apply to each element. |
var total = 0;
let err = await Utils.parallelEach(
[1, 2, 3],
async function(val, idx) {
var go = function() {
total += val;
};
if (idx === 1) {
await Utils.sleep(100);
go();
}
else {
go();
}
});
console.log(total); // == 6
root.parallelEach = async function (vals, fn) {
vals = vals || [];
let [err,res] = await root.parallelMap(vals, fn);
return err || null;
};
Runs an asynchronous function (mapping it) over each element in an array, in parallel. When all tasks have been completed or if an error occurs, function returns the resulting array.
Name | Type | Description |
---|---|---|
vals | Array | An array of values. |
fn | Function | A function (possibly asynchronous) to apply to each element. |
let [err, vals] = await Utils.parallelMap(
[1, 2, 3],
async function(val, idx) {
if (val === 2) {
await Utils.sleep(100);
return [null, val+1];
}
else {
return [null, val + 1];
}
});
console.log(vals); // == [2,3,4]
root.parallelMap = async function (vals, fn) {
vals = vals || [];
let tasks = [];
let createTask = function(val, idx) {
return function() { return fn(val, idx); };
};
for(let i = 0; i < vals.length; i++) {
tasks.push(createTask(vals[i], i));
}
return await root.parallel(tasks, true);
}
Runs multiple functions (tasks) in series. Each task takes the function as a parameter. When all tasks have been completed or if an error occurs, the function returns the combined results of all tasks in the order they were run.
Name | Type | Description |
---|---|---|
tasks | Function | An array of functions. |
fromMap | Boolean | set to true when method call is made from seriesMap function. (optional) |
var keeper = 0;
let [err, one, two] = awiat Utils.series([
async function() {
await Utils.sleep(10);
console.log(keeper++); // == 0
return [null, 1];
},
function() {
console.log(keeper++); // == 1
return [null, 2, 3];
}]
);
console.log(err); // == null
console.log(one); // == 1
console.log(two); // == [2, 3]
root.series = async function (tasks, fromMap) {
let res = [];
if(!root.isArray(tasks)&& root.isFunction(fromMap)){
let taskList = [];
Object.keys(arguments).forEach(key => {
taskList.push(arguments[key]);
});
tasks = taskList;
fromMap = false;
}
for(let task of tasks) {
let result = await task();
if(result){
if(result[0]){
return [result[0], null];
}
if(result.length > 2){
res.push(result.slice(1));
}else{
res.push(result[1]);
}
}
}
return fromMap ? [null, res] : [null, ...res];
}
Applies an asynchronous function over each element in an array, in series. If an error occurs, the function returns an error.
Name | Type | Description |
---|---|---|
vals | Array | An array of values. |
fn | Function | A function (possibly asynchronous)to apply to each element. |
var results = [1, 3, 6];
var total = 0;
let err = await Utils.seriesEach(
[1, 2, 3],
function(val, idx) {
total += val;
console.log(total === results[idx]); //== true
});
console.log(total); //== 6
root.seriesEach = async function (vals, fn) {
vals = vals || [];
let [err,res] = await root.seriesMap(vals, fn);
return err || null;
};
})();
Runs an asynchronous function (mapping it) over each element in an array, in series. When all tasks have been completed or if an error occurs, function returns the resulting array.
Name | Type | Description |
---|---|---|
vals | Array | An array of values. |
fn | Function | A function (possibly asynchronous) to apply to each element. |
var keeper = 1;
let [err, vals] = await Utils.seriesMap(
[1, 2, 3],
function(val, idx) {
console.log(keeper++); // == 1, then 2, then 3
return [null, val + 1];
}
);
console.log(vals); // == [2,3,4];
root.seriesMap = async function (vals, fn) {
vals = vals || [];
let tasks = [];
let createTask = function(val, idx) {
return function() {
return fn(val, idx);
};
};
for(let i = 0; i < vals.length; i++) {
tasks.push(createTask(vals[i], i));
}
return await root.series(tasks, true);
}
can make a function to pause execution for a fixed amount of time
Name | Type | Description |
---|---|---|
ms | Number | The timeout period, in milliseconds. |
await Utils.sleep(1000);
root.sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Indicates whether a string starts with a specific prefix.
Name | Type | Description |
---|---|---|
original | String | The string to search in. |
prefix | String | The prefix to search for. |
true
if the string starts with the prefix, false
if not.
var starts = splunkjs.Utils.startsWith("splunk-foo", "splunk-");
root.startsWith = function(original, prefix) {
let matches = original.match("^" + prefix);
return matches && matches.length > 0 && matches[0] === prefix;
};
Converts an iterable to an array.
Name | Type | Description |
---|---|---|
iterable | Arguments | The iterable to convert. |
The converted array.
function() {
console.log(arguments instanceof Array); // false
var arr = console.log(splunkjs.Utils.toArray(arguments) instanceof Array); // true
}
root.toArray = function(iterable) {
return Array.prototype.slice.call(iterable);
};
Strips a string of all leading and trailing whitespace characters.
Name | Type | Description |
---|---|---|
str | String | The string to trim. |
The trimmed string.
var a = " aaa ";
var b = splunkjs.Utils.trim(a); //== "aaa"
root.trim = function(str) {
str = str || "";
if (String.prototype.trim) {
return String.prototype.trim.call(str);
}
else {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
};
Runs an asynchronous while
loop.
Name | Type | Description |
---|---|---|
condition | Function | A function that returns a boolean indicating whether the condition has been met. |
body | Function | A function that runs the body of the loop. |
let i = 0;
try {
await Utils.whilst(
function() { return i++ < 3; },
async function() {
await Utils.sleep(0);
});
} catch(err) {
console.log(err);
}
root.whilst = async function(condition, body){
condition = condition || function() { return false; };
body = body || function() { return; };
let iterationDone = function(err) {
if (err) {
throw err;
}
else {
return root.whilst(condition, body);
}
};
if(condition()){
return iterationDone(await body())
}else{
return null;
}
}