_baseConvert.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. var mapping = require('./_mapping'),
  2. mutateMap = mapping.mutate,
  3. fallbackHolder = require('./placeholder');
  4. /**
  5. * Creates a function, with an arity of `n`, that invokes `func` with the
  6. * arguments it receives.
  7. *
  8. * @private
  9. * @param {Function} func The function to wrap.
  10. * @param {number} n The arity of the new function.
  11. * @returns {Function} Returns the new function.
  12. */
  13. function baseArity(func, n) {
  14. return n == 2
  15. ? function(a, b) { return func.apply(undefined, arguments); }
  16. : function(a) { return func.apply(undefined, arguments); };
  17. }
  18. /**
  19. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  20. * any additional arguments.
  21. *
  22. * @private
  23. * @param {Function} func The function to cap arguments for.
  24. * @param {number} n The arity cap.
  25. * @returns {Function} Returns the new function.
  26. */
  27. function baseAry(func, n) {
  28. return n == 2
  29. ? function(a, b) { return func(a, b); }
  30. : function(a) { return func(a); };
  31. }
  32. /**
  33. * Creates a clone of `array`.
  34. *
  35. * @private
  36. * @param {Array} array The array to clone.
  37. * @returns {Array} Returns the cloned array.
  38. */
  39. function cloneArray(array) {
  40. var length = array ? array.length : 0,
  41. result = Array(length);
  42. while (length--) {
  43. result[length] = array[length];
  44. }
  45. return result;
  46. }
  47. /**
  48. * Creates a function that clones a given object using the assignment `func`.
  49. *
  50. * @private
  51. * @param {Function} func The assignment function.
  52. * @returns {Function} Returns the new cloner function.
  53. */
  54. function createCloner(func) {
  55. return function(object) {
  56. return func({}, object);
  57. };
  58. }
  59. /**
  60. * Creates a function that wraps `func` and uses `cloner` to clone the first
  61. * argument it receives.
  62. *
  63. * @private
  64. * @param {Function} func The function to wrap.
  65. * @param {Function} cloner The function to clone arguments.
  66. * @returns {Function} Returns the new immutable function.
  67. */
  68. function wrapImmutable(func, cloner) {
  69. return function() {
  70. var length = arguments.length;
  71. if (!length) {
  72. return;
  73. }
  74. var args = Array(length);
  75. while (length--) {
  76. args[length] = arguments[length];
  77. }
  78. var result = args[0] = cloner.apply(undefined, args);
  79. func.apply(undefined, args);
  80. return result;
  81. };
  82. }
  83. /**
  84. * The base implementation of `convert` which accepts a `util` object of methods
  85. * required to perform conversions.
  86. *
  87. * @param {Object} util The util object.
  88. * @param {string} name The name of the function to convert.
  89. * @param {Function} func The function to convert.
  90. * @param {Object} [options] The options object.
  91. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  92. * @param {boolean} [options.curry=true] Specify currying.
  93. * @param {boolean} [options.fixed=true] Specify fixed arity.
  94. * @param {boolean} [options.immutable=true] Specify immutable operations.
  95. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  96. * @returns {Function|Object} Returns the converted function or object.
  97. */
  98. function baseConvert(util, name, func, options) {
  99. var setPlaceholder,
  100. isLib = typeof name == 'function',
  101. isObj = name === Object(name);
  102. if (isObj) {
  103. options = func;
  104. func = name;
  105. name = undefined;
  106. }
  107. if (func == null) {
  108. throw new TypeError;
  109. }
  110. options || (options = {});
  111. var config = {
  112. 'cap': 'cap' in options ? options.cap : true,
  113. 'curry': 'curry' in options ? options.curry : true,
  114. 'fixed': 'fixed' in options ? options.fixed : true,
  115. 'immutable': 'immutable' in options ? options.immutable : true,
  116. 'rearg': 'rearg' in options ? options.rearg : true
  117. };
  118. var forceCurry = ('curry' in options) && options.curry,
  119. forceFixed = ('fixed' in options) && options.fixed,
  120. forceRearg = ('rearg' in options) && options.rearg,
  121. placeholder = isLib ? func : fallbackHolder,
  122. pristine = isLib ? func.runInContext() : undefined;
  123. var helpers = isLib ? func : {
  124. 'ary': util.ary,
  125. 'assign': util.assign,
  126. 'clone': util.clone,
  127. 'curry': util.curry,
  128. 'forEach': util.forEach,
  129. 'isArray': util.isArray,
  130. 'isFunction': util.isFunction,
  131. 'iteratee': util.iteratee,
  132. 'keys': util.keys,
  133. 'rearg': util.rearg,
  134. 'spread': util.spread,
  135. 'toInteger': util.toInteger,
  136. 'toPath': util.toPath
  137. };
  138. var ary = helpers.ary,
  139. assign = helpers.assign,
  140. clone = helpers.clone,
  141. curry = helpers.curry,
  142. each = helpers.forEach,
  143. isArray = helpers.isArray,
  144. isFunction = helpers.isFunction,
  145. keys = helpers.keys,
  146. rearg = helpers.rearg,
  147. spread = helpers.spread,
  148. toInteger = helpers.toInteger,
  149. toPath = helpers.toPath;
  150. var aryMethodKeys = keys(mapping.aryMethod);
  151. var wrappers = {
  152. 'castArray': function(castArray) {
  153. return function() {
  154. var value = arguments[0];
  155. return isArray(value)
  156. ? castArray(cloneArray(value))
  157. : castArray.apply(undefined, arguments);
  158. };
  159. },
  160. 'iteratee': function(iteratee) {
  161. return function() {
  162. var func = arguments[0],
  163. arity = arguments[1],
  164. result = iteratee(func, arity),
  165. length = result.length;
  166. if (config.cap && typeof arity == 'number') {
  167. arity = arity > 2 ? (arity - 2) : 1;
  168. return (length && length <= arity) ? result : baseAry(result, arity);
  169. }
  170. return result;
  171. };
  172. },
  173. 'mixin': function(mixin) {
  174. return function(source) {
  175. var func = this;
  176. if (!isFunction(func)) {
  177. return mixin(func, Object(source));
  178. }
  179. var pairs = [];
  180. each(keys(source), function(key) {
  181. if (isFunction(source[key])) {
  182. pairs.push([key, func.prototype[key]]);
  183. }
  184. });
  185. mixin(func, Object(source));
  186. each(pairs, function(pair) {
  187. var value = pair[1];
  188. if (isFunction(value)) {
  189. func.prototype[pair[0]] = value;
  190. } else {
  191. delete func.prototype[pair[0]];
  192. }
  193. });
  194. return func;
  195. };
  196. },
  197. 'nthArg': function(nthArg) {
  198. return function(n) {
  199. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  200. return curry(nthArg(n), arity);
  201. };
  202. },
  203. 'rearg': function(rearg) {
  204. return function(func, indexes) {
  205. var arity = indexes ? indexes.length : 0;
  206. return curry(rearg(func, indexes), arity);
  207. };
  208. },
  209. 'runInContext': function(runInContext) {
  210. return function(context) {
  211. return baseConvert(util, runInContext(context), options);
  212. };
  213. }
  214. };
  215. /*--------------------------------------------------------------------------*/
  216. /**
  217. * Casts `func` to a function with an arity capped iteratee if needed.
  218. *
  219. * @private
  220. * @param {string} name The name of the function to inspect.
  221. * @param {Function} func The function to inspect.
  222. * @returns {Function} Returns the cast function.
  223. */
  224. function castCap(name, func) {
  225. if (config.cap) {
  226. var indexes = mapping.iterateeRearg[name];
  227. if (indexes) {
  228. return iterateeRearg(func, indexes);
  229. }
  230. var n = !isLib && mapping.iterateeAry[name];
  231. if (n) {
  232. return iterateeAry(func, n);
  233. }
  234. }
  235. return func;
  236. }
  237. /**
  238. * Casts `func` to a curried function if needed.
  239. *
  240. * @private
  241. * @param {string} name The name of the function to inspect.
  242. * @param {Function} func The function to inspect.
  243. * @param {number} n The arity of `func`.
  244. * @returns {Function} Returns the cast function.
  245. */
  246. function castCurry(name, func, n) {
  247. return (forceCurry || (config.curry && n > 1))
  248. ? curry(func, n)
  249. : func;
  250. }
  251. /**
  252. * Casts `func` to a fixed arity function if needed.
  253. *
  254. * @private
  255. * @param {string} name The name of the function to inspect.
  256. * @param {Function} func The function to inspect.
  257. * @param {number} n The arity cap.
  258. * @returns {Function} Returns the cast function.
  259. */
  260. function castFixed(name, func, n) {
  261. if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {
  262. var data = mapping.methodSpread[name],
  263. start = data && data.start;
  264. return start === undefined ? ary(func, n) : spread(func, start);
  265. }
  266. return func;
  267. }
  268. /**
  269. * Casts `func` to an rearged function if needed.
  270. *
  271. * @private
  272. * @param {string} name The name of the function to inspect.
  273. * @param {Function} func The function to inspect.
  274. * @param {number} n The arity of `func`.
  275. * @returns {Function} Returns the cast function.
  276. */
  277. function castRearg(name, func, n) {
  278. return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))
  279. ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])
  280. : func;
  281. }
  282. /**
  283. * Creates a clone of `object` by `path`.
  284. *
  285. * @private
  286. * @param {Object} object The object to clone.
  287. * @param {Array|string} path The path to clone by.
  288. * @returns {Object} Returns the cloned object.
  289. */
  290. function cloneByPath(object, path) {
  291. path = toPath(path);
  292. var index = -1,
  293. length = path.length,
  294. lastIndex = length - 1,
  295. result = clone(Object(object)),
  296. nested = result;
  297. while (nested != null && ++index < length) {
  298. var key = path[index],
  299. value = nested[key];
  300. if (value != null) {
  301. nested[path[index]] = clone(index == lastIndex ? value : Object(value));
  302. }
  303. nested = nested[key];
  304. }
  305. return result;
  306. }
  307. /**
  308. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  309. * version with conversion `options` applied.
  310. *
  311. * @param {Object} [options] The options object. See `baseConvert` for more details.
  312. * @returns {Function} Returns the converted `lodash`.
  313. */
  314. function convertLib(options) {
  315. return _.runInContext.convert(options)(undefined);
  316. }
  317. /**
  318. * Create a converter function for `func` of `name`.
  319. *
  320. * @param {string} name The name of the function to convert.
  321. * @param {Function} func The function to convert.
  322. * @returns {Function} Returns the new converter function.
  323. */
  324. function createConverter(name, func) {
  325. var oldOptions = options;
  326. return function(options) {
  327. var newUtil = isLib ? pristine : helpers,
  328. newFunc = isLib ? pristine[name] : func,
  329. newOptions = assign(assign({}, oldOptions), options);
  330. return baseConvert(newUtil, name, newFunc, newOptions);
  331. };
  332. }
  333. /**
  334. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  335. * arguments, ignoring any additional arguments.
  336. *
  337. * @private
  338. * @param {Function} func The function to cap iteratee arguments for.
  339. * @param {number} n The arity cap.
  340. * @returns {Function} Returns the new function.
  341. */
  342. function iterateeAry(func, n) {
  343. return overArg(func, function(func) {
  344. return typeof func == 'function' ? baseAry(func, n) : func;
  345. });
  346. }
  347. /**
  348. * Creates a function that wraps `func` to invoke its iteratee with arguments
  349. * arranged according to the specified `indexes` where the argument value at
  350. * the first index is provided as the first argument, the argument value at
  351. * the second index is provided as the second argument, and so on.
  352. *
  353. * @private
  354. * @param {Function} func The function to rearrange iteratee arguments for.
  355. * @param {number[]} indexes The arranged argument indexes.
  356. * @returns {Function} Returns the new function.
  357. */
  358. function iterateeRearg(func, indexes) {
  359. return overArg(func, function(func) {
  360. var n = indexes.length;
  361. return baseArity(rearg(baseAry(func, n), indexes), n);
  362. });
  363. }
  364. /**
  365. * Creates a function that invokes `func` with its first argument transformed.
  366. *
  367. * @private
  368. * @param {Function} func The function to wrap.
  369. * @param {Function} transform The argument transform.
  370. * @returns {Function} Returns the new function.
  371. */
  372. function overArg(func, transform) {
  373. return function() {
  374. var length = arguments.length;
  375. if (!length) {
  376. return func();
  377. }
  378. var args = Array(length);
  379. while (length--) {
  380. args[length] = arguments[length];
  381. }
  382. var index = config.rearg ? 0 : (length - 1);
  383. args[index] = transform(args[index]);
  384. return func.apply(undefined, args);
  385. };
  386. }
  387. /**
  388. * Creates a function that wraps `func` and applys the conversions
  389. * rules by `name`.
  390. *
  391. * @private
  392. * @param {string} name The name of the function to wrap.
  393. * @param {Function} func The function to wrap.
  394. * @returns {Function} Returns the converted function.
  395. */
  396. function wrap(name, func) {
  397. name = mapping.aliasToReal[name] || name;
  398. var result,
  399. wrapped = func,
  400. wrapper = wrappers[name];
  401. if (wrapper) {
  402. wrapped = wrapper(func);
  403. }
  404. else if (config.immutable) {
  405. if (mutateMap.array[name]) {
  406. wrapped = wrapImmutable(func, cloneArray);
  407. }
  408. else if (mutateMap.object[name]) {
  409. wrapped = wrapImmutable(func, createCloner(func));
  410. }
  411. else if (mutateMap.set[name]) {
  412. wrapped = wrapImmutable(func, cloneByPath);
  413. }
  414. }
  415. each(aryMethodKeys, function(aryKey) {
  416. each(mapping.aryMethod[aryKey], function(otherName) {
  417. if (name == otherName) {
  418. var spreadData = mapping.methodSpread[name],
  419. afterRearg = spreadData && spreadData.afterRearg;
  420. result = afterRearg
  421. ? castFixed(name, castRearg(name, wrapped, aryKey), aryKey)
  422. : castRearg(name, castFixed(name, wrapped, aryKey), aryKey);
  423. result = castCap(name, result);
  424. result = castCurry(name, result, aryKey);
  425. return false;
  426. }
  427. });
  428. return !result;
  429. });
  430. result || (result = wrapped);
  431. if (result == func) {
  432. result = forceCurry ? curry(result, 1) : function() {
  433. return func.apply(this, arguments);
  434. };
  435. }
  436. result.convert = createConverter(name, func);
  437. if (mapping.placeholder[name]) {
  438. setPlaceholder = true;
  439. result.placeholder = func.placeholder = placeholder;
  440. }
  441. return result;
  442. }
  443. /*--------------------------------------------------------------------------*/
  444. if (!isObj) {
  445. return wrap(name, func);
  446. }
  447. var _ = func;
  448. // Convert methods by ary cap.
  449. var pairs = [];
  450. each(aryMethodKeys, function(aryKey) {
  451. each(mapping.aryMethod[aryKey], function(key) {
  452. var func = _[mapping.remap[key] || key];
  453. if (func) {
  454. pairs.push([key, wrap(key, func)]);
  455. }
  456. });
  457. });
  458. // Convert remaining methods.
  459. each(keys(_), function(key) {
  460. var func = _[key];
  461. if (typeof func == 'function') {
  462. var length = pairs.length;
  463. while (length--) {
  464. if (pairs[length][0] == key) {
  465. return;
  466. }
  467. }
  468. func.convert = createConverter(key, func);
  469. pairs.push([key, func]);
  470. }
  471. });
  472. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  473. each(pairs, function(pair) {
  474. _[pair[0]] = pair[1];
  475. });
  476. _.convert = convertLib;
  477. if (setPlaceholder) {
  478. _.placeholder = placeholder;
  479. }
  480. // Assign aliases.
  481. each(keys(_), function(key) {
  482. each(mapping.realToAlias[key] || [], function(alias) {
  483. _[alias] = _[key];
  484. });
  485. });
  486. return _;
  487. }
  488. module.exports = baseConvert;