Importing Lodash as a Script Include

bbarber9
Giga Expert

Hello all,

I was inspired by this video to try and import lodash   into ServiceNow as a script include. I was able to save the code as a script include, but I am unable to use it. the _ doesn't seem to be defined. Has anyone managed to do this or something similar?

5 REPLIES 5

I pasted the whole code into new Script Include named        LodashUtil

I called it into scripts background but it was throwing error

I am Using Utah version

Any comments or suggestions for the same

I am sharing the code here with the attached photo

 

var LodashUtil = Class.create();
LodashUtil.prototype = {
    initialize: function() {},

    /** Used as a safe reference for `undefined` in pre-ES5 environments. */
    //var undefined;
    /** Used as the semantic version number. */
    VERSION: '4.17.11',
    /** Error message constants. */
    FUNC_ERROR_TEXT: 'Expected a function',

    /** Used to compose bitmasks for value comparisons. */
    COMPARE_PARTIAL_FLAG: 1,
    COMPARE_UNORDERED_FLAG: 2,

    /** Used to compose bitmasks for function metadata. */
    WRAP_BIND_FLAG: 1,
    WRAP_PARTIAL_FLAG: 32,

    /** Used as references for various `Number` constants. */
    INFINITY: 1 / 0,
    MAX_SAFE_INTEGER: 9007199254740991,
    /** `Object#toString` result references. */
    argsTag: '[object Arguments]',
    arrayTag: '[object Array]',
    asyncTag: '[object AsyncFunction]',
    boolTag: '[object Boolean]',
    dateTag: '[object Date]',
    errorTag: '[object Error]',
    funcTag: '[object Function]',
    genTag: '[object GeneratorFunction]',
    numberTag: '[object Number]',
    objectTag: '[object Object]',
    proxyTag: '[object Proxy]',
    regexpTag: '[object RegExp]',
    stringTag: '[object String]',
    /** Used to match HTML entities and HTML characters. */
    reUnescapedHtml: /[&<>"']/g,
    reHasUnescapedHtml: RegExp(reUnescapedHtml.source),

    /** Used to detect unsigned integer values. */
    reIsUint: /^(?:0|[1-9]\d*)$/,

    /** Used to map characters to HTML entities. */
    htmlEscapes: {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
    },

    /** Detect free variable `global` from Node.js. */
    freeGlobal: typeof global == 'object' && global && global.Object === Object && global,

    /** Detect free variable `self`. */
    freeSelf: typeof self == 'object' && self && self.Object === Object && self,

    /** Used as a reference to the global object. */
    root: freeGlobal || freeSelf || Function('return this')(),

    /** Detect free variable `exports`. */
    freeExports: typeof exports == 'object' && exports && !exports.nodeType && exports,

    /** Detect free variable `module`. */
    freeModule: freeExports && typeof module == 'object' && module && !module.nodeType && module,

    /** Used for built-in method references. */
    arrayProto: Array.prototype,
    objectProto: Object.prototype,

    /** Used to check objects for own properties. */
    hasOwnProperty: objectProto.hasOwnProperty,

    /** Used to generate unique IDs. */
    idCounter: 0,

    /**
     * Used to resolve the
     * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
     * of values.
     */
    nativeObjectToString: objectProto.toString,

    /** Used to restore the original `_` reference in `_.noConflict`. */
    oldDash: root._,

    /** Built-in value references. */
    objectCreate: Object.create,
    propertyIsEnumerable: objectProto.propertyIsEnumerable,

    /* Built-in method references for those with the same name as other `lodash` methods. */
    nativeIsFinite: root.isFinite,
    nativeKeys: overArg(Object.keys, Object),
    nativeMax: Math.max,
    /**
     * Appends the elements of `values` to `array`.
     *
     * @private
     * @Param {Array} array The array to modify.
     * @Param {Array} values The values to append.
     * @returns {Array} Returns `array`.
     */
    arrayPush: function(array, values) {
        array.push.apply(array, values);
        return array;
    },
    /**
     * The base implementation of `_.findIndex` and `_.findLastIndex` without
     * support for iteratee shorthands.
     *
     * @private
     * @Param {Array} array The array to inspect.
     * @Param {Function} predicate The function invoked per iteration.
     * @Param {number} fromIndex The index to search from.
     * @Param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {number} Returns the index of the matched value, else `-1`.
     */
    baseFindIndex: function(array, predicate, fromIndex, fromRight) {
        var length = array.length,
            index = fromIndex + (fromRight ? 1 : -1);
        while ((fromRight ? index-- : ++index < length)) {
            if (predicate(array[index], index, array)) {
                return index;
            }
        }
        return -1;
    },
    /**
     * The base implementation of `_.property` without support for deep paths.
     *
     * @private
     * @Param {string} key The key of the property to get.
     * @returns {Function} Returns the new accessor function.
     */
    baseProperty: function(key) {
        return function(object) {
            return object == null ? undefined : object[key];
        };
    },
    /**
     * The base implementation of `_.propertyOf` without support for deep paths.
     *
     * @private
     * @Param {Object} object The object to query.
     * @returns {Function} Returns the new accessor function.
     */
    basePropertyOf: function(object) {
        return function(key) {
            return object == null ? undefined : object[key];
        };
    },

    /**
     * The base implementation of `_.reduce` and `_.reduceRight`, without support
     * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
     *
     * @private
     * @Param {Array|Object} collection The collection to iterate over.
     * @Param {Function} iteratee The function invoked per iteration.
     * @Param {*} accumulator The initial value.
     * @Param {boolean} initAccum Specify using the first or last element of
     *  `collection` as the initial value.
     * @Param {Function} eachFunc The function to iterate over `collection`.
     * @returns {*} Returns the accumulated value.
     */
    baseReduce: function(collection, iteratee, accumulator, initAccum, eachFunc) {
        eachFunc(collection, function(value, index, collection) {
            accumulator = initAccum ?
                (initAccum = false, value) :
                iteratee(accumulator, value, index, collection);
        });
        return accumulator;
    },

    /**
     * The base implementation of `_.values` and `_.valuesIn` which creates an
     * array of `object` property values corresponding to the property names
     * of `props`.
     *
     * @private
     * @Param {Object} object The object to query.
     * @Param {Array} props The property names to get values for.
     * @returns {Object} Returns the array of property values.
     */
    baseValues: function(object, props) {
        return baseMap(props, function(key) {
            return object[key];
        });
    },
    /**
     * Used by `_.escape` to convert characters to HTML entities.
     *
     * @private
     * @Param {string} chr The matched character to escape.
     * @returns {string} Returns the escaped character.
     */
    escapeHtmlChar: basePropertyOf(htmlEscapes),

    /**
     * Creates a unary function that invokes `func` with its argument transformed.
     *
     * @private
     * @Param {Function} func The function to wrap.
     * @Param {Function} transform The argument transform.
     * @returns {Function} Returns the new function.
     */
    overArg: function(func, transform) {
        return function(arg) {
            return func(transform(arg));
        };
    },
    /*------------------------------------------------------------------------*/
    /**
     * Creates a `lodash` object which wraps `value` to enable implicit method
     * chain sequences. Methods that operate on and return arrays, collections,
     * and functions can be chained together. Methods that retrieve a single value
     * or may return a primitive value will automatically end the chain sequence
     * and return the unwrapped value. Otherwise, the value must be unwrapped
     * with `_#value`.
     * Explicit chain sequences, which must be unwrapped with `_#value`, may be
     * enabled using `_.chain`.
     * The execution of chained methods is lazy, that is, it's deferred until
     * `_#value` is implicitly or explicitly called.
     * Lazy evaluation allows several methods to support shortcut fusion.
     * Shortcut fusion is an optimization to merge iteratee calls; this avoids
     * the creation of intermediate arrays and can greatly reduce the number of
     * iteratee executions. Sections of a chain sequence qualify for shortcut
     * fusion if the section is applied to an array and iteratees accept only
     * one argument. The heuristic for whether a section qualifies for shortcut
     * fusion is subject to change.
     * Chaining is supported in custom builds as long as the `_#value` method is
     * directly or indirectly included in the build.
     * In addition to lodash methods, wrappers have `Array` and `String` methods.
     * The wrapper `Array` methods are:
     * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
     * The wrapper `String` methods are:
     * `replace` and `split`
     * The wrapper methods that support shortcut fusion are:
     * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
     * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
     * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
     * The chainable wrapper methods are:
     * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
     * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
     * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
     * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
     * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
     * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
     * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
     * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
     * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
     * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
     * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
     * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
     * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
     * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
     * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
     * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
     * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
     * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
     * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
     * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
     * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
     * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
     * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
     * `zipObject`, `zipObjectDeep`, and `zipWith`
     * The wrapper methods that are **not** chainable by default are:
     * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
     * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
     * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
     * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
     * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
     * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
     * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
     * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
     * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
     * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
     * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
     * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
     * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
     * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
     * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
     * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
     * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
     * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
     * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
     * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
     * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
     * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
     * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
     * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
     * `upperFirst`, `value`, and `words`
     * @Name _
     * @constructor
     * @category Seq
     * @Param {*} value The value to wrap in a `lodash` instance.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     * function square(n) {
     *   return n * n;
     * }
     * var wrapped = _([1, 2, 3]);
     * // Returns an unwrapped value.
     * wrapped.reduce(_.add);
     * // => 6
     * // Returns a wrapped value.
     * var squares = wrapped.map(square);
     * _.isArray(squares);
     * // => false
     * _.isArray(squares.value());
     * // => true
     */
    lodash: function(value) {
        return value instanceof LodashWrapper ?
            value :
            new LodashWrapper(value);
    },
    /**
     * The base implementation of `_.create` without support for assigning
     * properties to the created object.
     * @private
     * @Param {Object} proto The object to inherit from.
     * @returns {Object} Returns the new object.
     */
    baseCreate: (function() {
        function object() {}
        return function(proto) {
            if (!isObject(proto)) {
                return {};
            }
            if (objectCreate) {
                return objectCreate(proto);
            }
            object.prototype = proto;
            var result = new object;
            object.prototype = undefined;
            return result;
        };
    }()),
    type: "LodashUtil"
};

 

image.png