Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var arrayCopy = require('../internal/arrayCopy'),
2
baseFunctions = require('../internal/baseFunctions'),
3
isFunction = require('../lang/isFunction'),
4
isObject = require('../lang/isObject'),
5
keys = require('../object/keys');
6
7
/** Used for native method references. */
8
var arrayProto = Array.prototype;
9
10
/** Native method references. */
11
var push = arrayProto.push;
12
13
/**
14
* Adds all own enumerable function properties of a source object to the
15
* destination object. If `object` is a function then methods are added to
16
* its prototype as well.
17
*
18
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
19
* avoid conflicts caused by modifying the original.
20
*
21
* @static
22
* @memberOf _
23
* @category Utility
24
* @param {Function|Object} [object=lodash] The destination object.
25
* @param {Object} source The object of functions to add.
26
* @param {Object} [options] The options object.
27
* @param {boolean} [options.chain=true] Specify whether the functions added
28
* are chainable.
29
* @returns {Function|Object} Returns `object`.
30
* @example
31
*
32
* function vowels(string) {
33
* return _.filter(string, function(v) {
34
* return /[aeiou]/i.test(v);
35
* });
36
* }
37
*
38
* _.mixin({ 'vowels': vowels });
39
* _.vowels('fred');
40
* // => ['e']
41
*
42
* _('fred').vowels().value();
43
* // => ['e']
44
*
45
* _.mixin({ 'vowels': vowels }, { 'chain': false });
46
* _('fred').vowels();
47
* // => ['e']
48
*/
49
function mixin(object, source, options) {
50
var methodNames = baseFunctions(source, keys(source));
51
52
var chain = true,
53
index = -1,
54
isFunc = isFunction(object),
55
length = methodNames.length;
56
57
if (options === false) {
58
chain = false;
59
} else if (isObject(options) && 'chain' in options) {
60
chain = options.chain;
61
}
62
while (++index < length) {
63
var methodName = methodNames[index],
64
func = source[methodName];
65
66
object[methodName] = func;
67
if (isFunc) {
68
object.prototype[methodName] = (function(func) {
69
return function() {
70
var chainAll = this.__chain__;
71
if (chain || chainAll) {
72
var result = object(this.__wrapped__),
73
actions = result.__actions__ = arrayCopy(this.__actions__);
74
75
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
76
result.__chain__ = chainAll;
77
return result;
78
}
79
var args = [this.value()];
80
push.apply(args, arguments);
81
return func.apply(object, args);
82
};
83
}(func));
84
}
85
}
86
return object;
87
}
88
89
module.exports = mixin;
90
91