UNPKG

28.4 kBJavaScriptView Raw
1function _isPlaceholder(a) {
2 return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true;
3}
4
5/**
6 * Optimized internal one-arity curry function.
7 *
8 * @private
9 * @category Function
10 * @param {Function} fn The function to curry.
11 * @return {Function} The curried function.
12 */
13function _curry1(fn) {
14 return function f1(a) {
15 if (arguments.length === 0 || _isPlaceholder(a)) {
16 return f1;
17 } else {
18 return fn.apply(this, arguments);
19 }
20 };
21}
22
23/**
24 * Optimized internal two-arity curry function.
25 *
26 * @private
27 * @category Function
28 * @param {Function} fn The function to curry.
29 * @return {Function} The curried function.
30 */
31function _curry2(fn) {
32 return function f2(a, b) {
33 switch (arguments.length) {
34 case 0:
35 return f2;
36 case 1:
37 return _isPlaceholder(a) ? f2 : _curry1(function (_b) {
38 return fn(a, _b);
39 });
40 default:
41 return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {
42 return fn(_a, b);
43 }) : _isPlaceholder(b) ? _curry1(function (_b) {
44 return fn(a, _b);
45 }) : fn(a, b);
46 }
47 };
48}
49
50/**
51 * Private `concat` function to merge two array-like objects.
52 *
53 * @private
54 * @param {Array|Arguments} [set1=[]] An array-like object.
55 * @param {Array|Arguments} [set2=[]] An array-like object.
56 * @return {Array} A new, merged array.
57 * @example
58 *
59 * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
60 */
61function _concat(set1, set2) {
62 set1 = set1 || [];
63 set2 = set2 || [];
64 var idx;
65 var len1 = set1.length;
66 var len2 = set2.length;
67 var result = [];
68
69 idx = 0;
70 while (idx < len1) {
71 result[result.length] = set1[idx];
72 idx += 1;
73 }
74 idx = 0;
75 while (idx < len2) {
76 result[result.length] = set2[idx];
77 idx += 1;
78 }
79 return result;
80}
81
82function _arity(n, fn) {
83 /* eslint-disable no-unused-vars */
84 switch (n) {
85 case 0:
86 return function () {
87 return fn.apply(this, arguments);
88 };
89 case 1:
90 return function (a0) {
91 return fn.apply(this, arguments);
92 };
93 case 2:
94 return function (a0, a1) {
95 return fn.apply(this, arguments);
96 };
97 case 3:
98 return function (a0, a1, a2) {
99 return fn.apply(this, arguments);
100 };
101 case 4:
102 return function (a0, a1, a2, a3) {
103 return fn.apply(this, arguments);
104 };
105 case 5:
106 return function (a0, a1, a2, a3, a4) {
107 return fn.apply(this, arguments);
108 };
109 case 6:
110 return function (a0, a1, a2, a3, a4, a5) {
111 return fn.apply(this, arguments);
112 };
113 case 7:
114 return function (a0, a1, a2, a3, a4, a5, a6) {
115 return fn.apply(this, arguments);
116 };
117 case 8:
118 return function (a0, a1, a2, a3, a4, a5, a6, a7) {
119 return fn.apply(this, arguments);
120 };
121 case 9:
122 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
123 return fn.apply(this, arguments);
124 };
125 case 10:
126 return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
127 return fn.apply(this, arguments);
128 };
129 default:
130 throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
131 }
132}
133
134/**
135 * Internal curryN function.
136 *
137 * @private
138 * @category Function
139 * @param {Number} length The arity of the curried function.
140 * @param {Array} received An array of arguments received thus far.
141 * @param {Function} fn The function to curry.
142 * @return {Function} The curried function.
143 */
144function _curryN(length, received, fn) {
145 return function () {
146 var combined = [];
147 var argsIdx = 0;
148 var left = length;
149 var combinedIdx = 0;
150 while (combinedIdx < received.length || argsIdx < arguments.length) {
151 var result;
152 if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) {
153 result = received[combinedIdx];
154 } else {
155 result = arguments[argsIdx];
156 argsIdx += 1;
157 }
158 combined[combinedIdx] = result;
159 if (!_isPlaceholder(result)) {
160 left -= 1;
161 }
162 combinedIdx += 1;
163 }
164 return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn));
165 };
166}
167
168/**
169 * Returns a curried equivalent of the provided function, with the specified
170 * arity. The curried function has two unusual capabilities. First, its
171 * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the
172 * following are equivalent:
173 *
174 * - `g(1)(2)(3)`
175 * - `g(1)(2, 3)`
176 * - `g(1, 2)(3)`
177 * - `g(1, 2, 3)`
178 *
179 * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
180 * "gaps", allowing partial application of any combination of arguments,
181 * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
182 * the following are equivalent:
183 *
184 * - `g(1, 2, 3)`
185 * - `g(_, 2, 3)(1)`
186 * - `g(_, _, 3)(1)(2)`
187 * - `g(_, _, 3)(1, 2)`
188 * - `g(_, 2)(1)(3)`
189 * - `g(_, 2)(1, 3)`
190 * - `g(_, 2)(_, 3)(1)`
191 *
192 * @func
193 * @memberOf R
194 * @since v0.5.0
195 * @category Function
196 * @sig Number -> (* -> a) -> (* -> a)
197 * @param {Number} length The arity for the returned function.
198 * @param {Function} fn The function to curry.
199 * @return {Function} A new, curried function.
200 * @see R.curry
201 * @example
202 *
203 * const sumArgs = (...args) => R.sum(args);
204 *
205 * const curriedAddFourNumbers = R.curryN(4, sumArgs);
206 * const f = curriedAddFourNumbers(1, 2);
207 * const g = f(3);
208 * g(4); //=> 10
209 */
210var curryN = /*#__PURE__*/_curry2(function curryN(length, fn) {
211 if (length === 1) {
212 return _curry1(fn);
213 }
214 return _arity(length, _curryN(length, [], fn));
215});
216
217/**
218 * Tests whether or not an object is an array.
219 *
220 * @private
221 * @param {*} val The object to test.
222 * @return {Boolean} `true` if `val` is an array, `false` otherwise.
223 * @example
224 *
225 * _isArray([]); //=> true
226 * _isArray(null); //=> false
227 * _isArray({}); //=> false
228 */
229var _isArray = Array.isArray || function _isArray(val) {
230 return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';
231};
232
233function _isTransformer(obj) {
234 return obj != null && typeof obj['@@transducer/step'] === 'function';
235}
236
237/**
238 * Returns a function that dispatches with different strategies based on the
239 * object in list position (last argument). If it is an array, executes [fn].
240 * Otherwise, if it has a function with one of the given method names, it will
241 * execute that function (functor case). Otherwise, if it is a transformer,
242 * uses transducer [xf] to return a new transformer (transducer case).
243 * Otherwise, it will default to executing [fn].
244 *
245 * @private
246 * @param {Array} methodNames properties to check for a custom implementation
247 * @param {Function} xf transducer to initialize if object is transformer
248 * @param {Function} fn default ramda implementation
249 * @return {Function} A function that dispatches on object in list position
250 */
251function _dispatchable(methodNames, xf, fn) {
252 return function () {
253 if (arguments.length === 0) {
254 return fn();
255 }
256 var args = Array.prototype.slice.call(arguments, 0);
257 var obj = args.pop();
258 if (!_isArray(obj)) {
259 var idx = 0;
260 while (idx < methodNames.length) {
261 if (typeof obj[methodNames[idx]] === 'function') {
262 return obj[methodNames[idx]].apply(obj, args);
263 }
264 idx += 1;
265 }
266 if (_isTransformer(obj)) {
267 var transducer = xf.apply(null, args);
268 return transducer(obj);
269 }
270 }
271 return fn.apply(this, arguments);
272 };
273}
274
275var _xfBase = {
276 init: function () {
277 return this.xf['@@transducer/init']();
278 },
279 result: function (result) {
280 return this.xf['@@transducer/result'](result);
281 }
282};
283
284function _map(fn, functor) {
285 var idx = 0;
286 var len = functor.length;
287 var result = Array(len);
288 while (idx < len) {
289 result[idx] = fn(functor[idx]);
290 idx += 1;
291 }
292 return result;
293}
294
295function _isString(x) {
296 return Object.prototype.toString.call(x) === '[object String]';
297}
298
299/**
300 * Tests whether or not an object is similar to an array.
301 *
302 * @private
303 * @category Type
304 * @category List
305 * @sig * -> Boolean
306 * @param {*} x The object to test.
307 * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
308 * @example
309 *
310 * _isArrayLike([]); //=> true
311 * _isArrayLike(true); //=> false
312 * _isArrayLike({}); //=> false
313 * _isArrayLike({length: 10}); //=> false
314 * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
315 */
316var _isArrayLike = /*#__PURE__*/_curry1(function isArrayLike(x) {
317 if (_isArray(x)) {
318 return true;
319 }
320 if (!x) {
321 return false;
322 }
323 if (typeof x !== 'object') {
324 return false;
325 }
326 if (_isString(x)) {
327 return false;
328 }
329 if (x.nodeType === 1) {
330 return !!x.length;
331 }
332 if (x.length === 0) {
333 return true;
334 }
335 if (x.length > 0) {
336 return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
337 }
338 return false;
339});
340
341var XWrap = /*#__PURE__*/function () {
342 function XWrap(fn) {
343 this.f = fn;
344 }
345 XWrap.prototype['@@transducer/init'] = function () {
346 throw new Error('init not implemented on XWrap');
347 };
348 XWrap.prototype['@@transducer/result'] = function (acc) {
349 return acc;
350 };
351 XWrap.prototype['@@transducer/step'] = function (acc, x) {
352 return this.f(acc, x);
353 };
354
355 return XWrap;
356}();
357
358function _xwrap(fn) {
359 return new XWrap(fn);
360}
361
362/**
363 * Creates a function that is bound to a context.
364 * Note: `R.bind` does not provide the additional argument-binding capabilities of
365 * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
366 *
367 * @func
368 * @memberOf R
369 * @since v0.6.0
370 * @category Function
371 * @category Object
372 * @sig (* -> *) -> {*} -> (* -> *)
373 * @param {Function} fn The function to bind to context
374 * @param {Object} thisObj The context to bind `fn` to
375 * @return {Function} A function that will execute in the context of `thisObj`.
376 * @see R.partial
377 * @example
378 *
379 * const log = R.bind(console.log, console);
380 * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3}
381 * // logs {a: 2}
382 * @symb R.bind(f, o)(a, b) = f.call(o, a, b)
383 */
384var bind = /*#__PURE__*/_curry2(function bind(fn, thisObj) {
385 return _arity(fn.length, function () {
386 return fn.apply(thisObj, arguments);
387 });
388});
389
390function _arrayReduce(xf, acc, list) {
391 var idx = 0;
392 var len = list.length;
393 while (idx < len) {
394 acc = xf['@@transducer/step'](acc, list[idx]);
395 if (acc && acc['@@transducer/reduced']) {
396 acc = acc['@@transducer/value'];
397 break;
398 }
399 idx += 1;
400 }
401 return xf['@@transducer/result'](acc);
402}
403
404function _iterableReduce(xf, acc, iter) {
405 var step = iter.next();
406 while (!step.done) {
407 acc = xf['@@transducer/step'](acc, step.value);
408 if (acc && acc['@@transducer/reduced']) {
409 acc = acc['@@transducer/value'];
410 break;
411 }
412 step = iter.next();
413 }
414 return xf['@@transducer/result'](acc);
415}
416
417function _methodReduce(xf, acc, obj, methodName) {
418 return xf['@@transducer/result'](obj[methodName](bind(xf['@@transducer/step'], xf), acc));
419}
420
421var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';
422
423function _reduce(fn, acc, list) {
424 if (typeof fn === 'function') {
425 fn = _xwrap(fn);
426 }
427 if (_isArrayLike(list)) {
428 return _arrayReduce(fn, acc, list);
429 }
430 if (typeof list['fantasy-land/reduce'] === 'function') {
431 return _methodReduce(fn, acc, list, 'fantasy-land/reduce');
432 }
433 if (list[symIterator] != null) {
434 return _iterableReduce(fn, acc, list[symIterator]());
435 }
436 if (typeof list.next === 'function') {
437 return _iterableReduce(fn, acc, list);
438 }
439 if (typeof list.reduce === 'function') {
440 return _methodReduce(fn, acc, list, 'reduce');
441 }
442
443 throw new TypeError('reduce: list must be array or iterable');
444}
445
446var XMap = /*#__PURE__*/function () {
447 function XMap(f, xf) {
448 this.xf = xf;
449 this.f = f;
450 }
451 XMap.prototype['@@transducer/init'] = _xfBase.init;
452 XMap.prototype['@@transducer/result'] = _xfBase.result;
453 XMap.prototype['@@transducer/step'] = function (result, input) {
454 return this.xf['@@transducer/step'](result, this.f(input));
455 };
456
457 return XMap;
458}();
459
460var _xmap = /*#__PURE__*/_curry2(function _xmap(f, xf) {
461 return new XMap(f, xf);
462});
463
464function _has(prop, obj) {
465 return Object.prototype.hasOwnProperty.call(obj, prop);
466}
467
468var toString = Object.prototype.toString;
469var _isArguments = /*#__PURE__*/function () {
470 return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) {
471 return toString.call(x) === '[object Arguments]';
472 } : function _isArguments(x) {
473 return _has('callee', x);
474 };
475}();
476
477// cover IE < 9 keys issues
478var hasEnumBug = ! /*#__PURE__*/{ toString: null }.propertyIsEnumerable('toString');
479var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
480// Safari bug
481var hasArgsEnumBug = /*#__PURE__*/function () {
482
483 return arguments.propertyIsEnumerable('length');
484}();
485
486var contains = function contains(list, item) {
487 var idx = 0;
488 while (idx < list.length) {
489 if (list[idx] === item) {
490 return true;
491 }
492 idx += 1;
493 }
494 return false;
495};
496
497/**
498 * Returns a list containing the names of all the enumerable own properties of
499 * the supplied object.
500 * Note that the order of the output array is not guaranteed to be consistent
501 * across different JS platforms.
502 *
503 * @func
504 * @memberOf R
505 * @since v0.1.0
506 * @category Object
507 * @sig {k: v} -> [k]
508 * @param {Object} obj The object to extract properties from
509 * @return {Array} An array of the object's own properties.
510 * @see R.keysIn, R.values
511 * @example
512 *
513 * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
514 */
515var keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? /*#__PURE__*/_curry1(function keys(obj) {
516 return Object(obj) !== obj ? [] : Object.keys(obj);
517}) : /*#__PURE__*/_curry1(function keys(obj) {
518 if (Object(obj) !== obj) {
519 return [];
520 }
521 var prop, nIdx;
522 var ks = [];
523 var checkArgsLength = hasArgsEnumBug && _isArguments(obj);
524 for (prop in obj) {
525 if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) {
526 ks[ks.length] = prop;
527 }
528 }
529 if (hasEnumBug) {
530 nIdx = nonEnumerableProps.length - 1;
531 while (nIdx >= 0) {
532 prop = nonEnumerableProps[nIdx];
533 if (_has(prop, obj) && !contains(ks, prop)) {
534 ks[ks.length] = prop;
535 }
536 nIdx -= 1;
537 }
538 }
539 return ks;
540});
541
542/**
543 * Takes a function and
544 * a [functor](https://github.com/fantasyland/fantasy-land#functor),
545 * applies the function to each of the functor's values, and returns
546 * a functor of the same shape.
547 *
548 * Ramda provides suitable `map` implementations for `Array` and `Object`,
549 * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`.
550 *
551 * Dispatches to the `map` method of the second argument, if present.
552 *
553 * Acts as a transducer if a transformer is given in list position.
554 *
555 * Also treats functions as functors and will compose them together.
556 *
557 * @func
558 * @memberOf R
559 * @since v0.1.0
560 * @category List
561 * @sig Functor f => (a -> b) -> f a -> f b
562 * @param {Function} fn The function to be called on every element of the input `list`.
563 * @param {Array} list The list to be iterated over.
564 * @return {Array} The new list.
565 * @see R.transduce, R.addIndex
566 * @example
567 *
568 * const double = x => x * 2;
569 *
570 * R.map(double, [1, 2, 3]); //=> [2, 4, 6]
571 *
572 * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}
573 * @symb R.map(f, [a, b]) = [f(a), f(b)]
574 * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) }
575 * @symb R.map(f, functor_o) = functor_o.map(f)
576 */
577var map = /*#__PURE__*/_curry2( /*#__PURE__*/_dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) {
578 switch (Object.prototype.toString.call(functor)) {
579 case '[object Function]':
580 return curryN(functor.length, function () {
581 return fn.call(this, functor.apply(this, arguments));
582 });
583 case '[object Object]':
584 return _reduce(function (acc, key) {
585 acc[key] = fn(functor[key]);
586 return acc;
587 }, {}, keys(functor));
588 default:
589 return _map(fn, functor);
590 }
591}));
592
593/**
594 * ap applies a list of functions to a list of values.
595 *
596 * Dispatches to the `ap` method of the second argument, if present. Also
597 * treats curried functions as applicatives.
598 *
599 * @func
600 * @memberOf R
601 * @since v0.3.0
602 * @category Function
603 * @sig [a -> b] -> [a] -> [b]
604 * @sig Apply f => f (a -> b) -> f a -> f b
605 * @sig (r -> a -> b) -> (r -> a) -> (r -> b)
606 * @param {*} applyF
607 * @param {*} applyX
608 * @return {*}
609 * @example
610 *
611 * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
612 * R.ap([R.concat('tasty '), R.toUpper], ['pizza', 'salad']); //=> ["tasty pizza", "tasty salad", "PIZZA", "SALAD"]
613 *
614 * // R.ap can also be used as S combinator
615 * // when only two functions are passed
616 * R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA'
617 * @symb R.ap([f, g], [a, b]) = [f(a), f(b), g(a), g(b)]
618 */
619var ap = /*#__PURE__*/_curry2(function ap(applyF, applyX) {
620 return typeof applyX['fantasy-land/ap'] === 'function' ? applyX['fantasy-land/ap'](applyF) : typeof applyF.ap === 'function' ? applyF.ap(applyX) : typeof applyF === 'function' ? function (x) {
621 return applyF(x)(applyX(x));
622 } : _reduce(function (acc, f) {
623 return _concat(acc, map(f, applyX));
624 }, [], applyF);
625});
626
627function _isFunction(x) {
628 return Object.prototype.toString.call(x) === '[object Function]';
629}
630
631/**
632 * "lifts" a function to be the specified arity, so that it may "map over" that
633 * many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
634 *
635 * @func
636 * @memberOf R
637 * @since v0.7.0
638 * @category Function
639 * @sig Number -> (*... -> *) -> ([*]... -> [*])
640 * @param {Function} fn The function to lift into higher context
641 * @return {Function} The lifted function.
642 * @see R.lift, R.ap
643 * @example
644 *
645 * const madd3 = R.liftN(3, (...args) => R.sum(args));
646 * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
647 */
648var liftN = /*#__PURE__*/_curry2(function liftN(arity, fn) {
649 var lifted = curryN(arity, fn);
650 return curryN(arity, function () {
651 return _reduce(ap, map(lifted, arguments[0]), Array.prototype.slice.call(arguments, 1));
652 });
653});
654
655/**
656 * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other
657 * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
658 *
659 * @func
660 * @memberOf R
661 * @since v0.7.0
662 * @category Function
663 * @sig (*... -> *) -> ([*]... -> [*])
664 * @param {Function} fn The function to lift into higher context
665 * @return {Function} The lifted function.
666 * @see R.liftN
667 * @example
668 *
669 * const madd3 = R.lift((a, b, c) => a + b + c);
670 *
671 * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
672 *
673 * const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e);
674 *
675 * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
676 */
677var lift = /*#__PURE__*/_curry1(function lift(fn) {
678 return liftN(fn.length, fn);
679});
680
681/**
682 * Returns `true` if one or both of its arguments are `true`. Returns `false`
683 * if both arguments are `false`.
684 *
685 * @func
686 * @memberOf R
687 * @since v0.1.0
688 * @category Logic
689 * @sig a -> b -> a | b
690 * @param {Any} a
691 * @param {Any} b
692 * @return {Any} the first argument if truthy, otherwise the second argument.
693 * @see R.either
694 * @example
695 *
696 * R.or(true, true); //=> true
697 * R.or(true, false); //=> true
698 * R.or(false, true); //=> true
699 * R.or(false, false); //=> false
700 */
701var or = /*#__PURE__*/_curry2(function or(a, b) {
702 return a || b;
703});
704
705/**
706 * A function wrapping calls to the two functions in an `||` operation,
707 * returning the result of the first function if it is truth-y and the result
708 * of the second function otherwise. Note that this is short-circuited,
709 * meaning that the second function will not be invoked if the first returns a
710 * truth-y value.
711 *
712 * In addition to functions, `R.either` also accepts any fantasy-land compatible
713 * applicative functor.
714 *
715 * @func
716 * @memberOf R
717 * @since v0.12.0
718 * @category Logic
719 * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
720 * @param {Function} f a predicate
721 * @param {Function} g another predicate
722 * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
723 * @see R.or
724 * @example
725 *
726 * const gt10 = x => x > 10;
727 * const even = x => x % 2 === 0;
728 * const f = R.either(gt10, even);
729 * f(101); //=> true
730 * f(8); //=> true
731 *
732 * R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55)
733 * R.either([false, false, 'a'], [11]) // => [11, 11, "a"]
734 */
735var either = /*#__PURE__*/_curry2(function either(f, g) {
736 return _isFunction(f) ? function _either() {
737 return f.apply(this, arguments) || g.apply(this, arguments);
738 } : lift(or)(f, g);
739});
740
741/** Detect free variable `global` from Node.js. */
742var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
743
744/** Detect free variable `self`. */
745var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
746
747/** Used as a reference to the global object. */
748var root = freeGlobal || freeSelf || Function('return this')();
749
750/** Built-in value references. */
751var Symbol$1 = root.Symbol;
752
753/** Used for built-in method references. */
754var objectProto = Object.prototype;
755
756/** Used to check objects for own properties. */
757var hasOwnProperty = objectProto.hasOwnProperty;
758
759/**
760 * Used to resolve the
761 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
762 * of values.
763 */
764var nativeObjectToString = objectProto.toString;
765
766/** Built-in value references. */
767var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
768
769/**
770 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
771 *
772 * @private
773 * @param {*} value The value to query.
774 * @returns {string} Returns the raw `toStringTag`.
775 */
776function getRawTag(value) {
777 var isOwn = hasOwnProperty.call(value, symToStringTag),
778 tag = value[symToStringTag];
779
780 try {
781 value[symToStringTag] = undefined;
782 var unmasked = true;
783 } catch (e) {}
784
785 var result = nativeObjectToString.call(value);
786 if (unmasked) {
787 if (isOwn) {
788 value[symToStringTag] = tag;
789 } else {
790 delete value[symToStringTag];
791 }
792 }
793 return result;
794}
795
796/** Used for built-in method references. */
797var objectProto$1 = Object.prototype;
798
799/**
800 * Used to resolve the
801 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
802 * of values.
803 */
804var nativeObjectToString$1 = objectProto$1.toString;
805
806/**
807 * Converts `value` to a string using `Object.prototype.toString`.
808 *
809 * @private
810 * @param {*} value The value to convert.
811 * @returns {string} Returns the converted string.
812 */
813function objectToString(value) {
814 return nativeObjectToString$1.call(value);
815}
816
817/** `Object#toString` result references. */
818var nullTag = '[object Null]',
819 undefinedTag = '[object Undefined]';
820
821/** Built-in value references. */
822var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
823
824/**
825 * The base implementation of `getTag` without fallbacks for buggy environments.
826 *
827 * @private
828 * @param {*} value The value to query.
829 * @returns {string} Returns the `toStringTag`.
830 */
831function baseGetTag(value) {
832 if (value == null) {
833 return value === undefined ? undefinedTag : nullTag;
834 }
835 return (symToStringTag$1 && symToStringTag$1 in Object(value))
836 ? getRawTag(value)
837 : objectToString(value);
838}
839
840/**
841 * Checks if `value` is the
842 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
843 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
844 *
845 * @static
846 * @memberOf _
847 * @since 0.1.0
848 * @category Lang
849 * @param {*} value The value to check.
850 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
851 * @example
852 *
853 * _.isObject({});
854 * // => true
855 *
856 * _.isObject([1, 2, 3]);
857 * // => true
858 *
859 * _.isObject(_.noop);
860 * // => true
861 *
862 * _.isObject(null);
863 * // => false
864 */
865function isObject(value) {
866 var type = typeof value;
867 return value != null && (type == 'object' || type == 'function');
868}
869
870/** `Object#toString` result references. */
871var asyncTag = '[object AsyncFunction]',
872 funcTag = '[object Function]',
873 genTag = '[object GeneratorFunction]',
874 proxyTag = '[object Proxy]';
875
876/**
877 * Checks if `value` is classified as a `Function` object.
878 *
879 * @static
880 * @memberOf _
881 * @since 0.1.0
882 * @category Lang
883 * @param {*} value The value to check.
884 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
885 * @example
886 *
887 * _.isFunction(_);
888 * // => true
889 *
890 * _.isFunction(/abc/);
891 * // => false
892 */
893function isFunction(value) {
894 if (!isObject(value)) {
895 return false;
896 }
897 // The use of `Object#toString` avoids issues with the `typeof` operator
898 // in Safari 9 which returns 'object' for typed arrays and other constructors.
899 var tag = baseGetTag(value);
900 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
901}
902
903/**
904 * Utility function mapping a Rollup config's `external` option into a function.
905
906 * In Rollup, the `external` config option can be provided as an array or a function.
907 * https://rollupjs.org/#peer-dependencies
908 *
909 * An `external` configuration in array format can be represented in the function
910 * format, but not vice-versa. This utility accepts either format and returns the
911 * function representation.
912 *
913 * @param {Array|Function} external The `external` property from Rollup's config.
914 * @returns {Function} Function equivalent of the passed in `external`.
915 */
916
917function externalToFn(external) {
918 if (isFunction(external)) {
919 return external;
920 } else if (Array.isArray(external)) {
921 return function (id) {
922 return external.some(function (module) {
923 return module === id;
924 });
925 };
926 } else {
927 throw new Error("rollup-plugin-peer-deps-external: 'external' option must be a function or an array.");
928 }
929}
930
931/**
932 * Creates a test function from a list of module names. The resulting function
933 * accepts a string id and returns whether it matches a module in the list.
934 *
935 * The string id can be a module name (e.g. `lodash`) or a
936 * "module path" (e.g. `lodash/map`).
937 *
938 * @param {Array} modulesNames Array of module names to match against.
939 * @returns {function(String): (boolean)} Predicate function accepting a string id.
940 */
941function getModulesMatcher(modulesNames) {
942 var regexps = modulesNames.map(moduleRegExp);
943 return function (id) {
944 return regexps.some(function (regexp) {
945 return regexp.test(id);
946 });
947 };
948}
949
950var moduleRegExp = function moduleRegExp(module) {
951 return new RegExp("^".concat(module, "(\\/.+)*$"));
952};
953
954var _require = require('path'),
955 resolve = _require.resolve;
956
957function getDeps() {
958 var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : resolve(process.cwd(), 'package.json');
959 var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'peerDependencies';
960
961 try {
962 var pkg = require(path);
963
964 return Object.keys(pkg[type]);
965 } catch (err) {
966 return [];
967 }
968}
969
970function PeerDepsExternalPlugin() {
971 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
972 packageJsonPath = _ref.packageJsonPath,
973 includeDependencies = _ref.includeDependencies;
974
975 return {
976 name: 'peer-deps-external',
977 options: function options(opts) {
978 opts.external = either( // Retain existing `external` config
979 externalToFn(opts.external), // Add `peerDependencies` to `external` config
980 getModulesMatcher(getDeps(packageJsonPath, 'peerDependencies').concat(includeDependencies ? getDeps(packageJsonPath, 'dependencies') : [])));
981 return opts;
982 }
983 };
984}
985
986export default PeerDepsExternalPlugin;