_baseConvert.js 16KB

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