_baseConvert.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. 'isFunction': util.isFunction,
  160. 'iteratee': util.iteratee,
  161. 'keys': util.keys,
  162. 'rearg': util.rearg,
  163. 'toInteger': util.toInteger,
  164. 'toPath': util.toPath
  165. };
  166. var ary = helpers.ary,
  167. assign = helpers.assign,
  168. clone = helpers.clone,
  169. curry = helpers.curry,
  170. each = helpers.forEach,
  171. isArray = helpers.isArray,
  172. isFunction = helpers.isFunction,
  173. keys = helpers.keys,
  174. rearg = helpers.rearg,
  175. toInteger = helpers.toInteger,
  176. toPath = helpers.toPath;
  177. var aryMethodKeys = keys(mapping.aryMethod);
  178. var wrappers = {
  179. 'castArray': function(castArray) {
  180. return function() {
  181. var value = arguments[0];
  182. return isArray(value)
  183. ? castArray(cloneArray(value))
  184. : castArray.apply(undefined, arguments);
  185. };
  186. },
  187. 'iteratee': function(iteratee) {
  188. return function() {
  189. var func = arguments[0],
  190. arity = arguments[1],
  191. result = iteratee(func, arity),
  192. length = result.length;
  193. if (config.cap && typeof arity == 'number') {
  194. arity = arity > 2 ? (arity - 2) : 1;
  195. return (length && length <= arity) ? result : baseAry(result, arity);
  196. }
  197. return result;
  198. };
  199. },
  200. 'mixin': function(mixin) {
  201. return function(source) {
  202. var func = this;
  203. if (!isFunction(func)) {
  204. return mixin(func, Object(source));
  205. }
  206. var pairs = [];
  207. each(keys(source), function(key) {
  208. if (isFunction(source[key])) {
  209. pairs.push([key, func.prototype[key]]);
  210. }
  211. });
  212. mixin(func, Object(source));
  213. each(pairs, function(pair) {
  214. var value = pair[1];
  215. if (isFunction(value)) {
  216. func.prototype[pair[0]] = value;
  217. } else {
  218. delete func.prototype[pair[0]];
  219. }
  220. });
  221. return func;
  222. };
  223. },
  224. 'nthArg': function(nthArg) {
  225. return function(n) {
  226. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  227. return curry(nthArg(n), arity);
  228. };
  229. },
  230. 'rearg': function(rearg) {
  231. return function(func, indexes) {
  232. var arity = indexes ? indexes.length : 0;
  233. return curry(rearg(func, indexes), arity);
  234. };
  235. },
  236. 'runInContext': function(runInContext) {
  237. return function(context) {
  238. return baseConvert(util, runInContext(context), options);
  239. };
  240. }
  241. };
  242. /*--------------------------------------------------------------------------*/
  243. /**
  244. * Casts `func` to a function with an arity capped iteratee if needed.
  245. *
  246. * @private
  247. * @param {string} name The name of the function to inspect.
  248. * @param {Function} func The function to inspect.
  249. * @returns {Function} Returns the cast function.
  250. */
  251. function castCap(name, func) {
  252. if (config.cap) {
  253. var indexes = mapping.iterateeRearg[name];
  254. if (indexes) {
  255. return iterateeRearg(func, indexes);
  256. }
  257. var n = !isLib && mapping.iterateeAry[name];
  258. if (n) {
  259. return iterateeAry(func, n);
  260. }
  261. }
  262. return func;
  263. }
  264. /**
  265. * Casts `func` to a curried function if needed.
  266. *
  267. * @private
  268. * @param {string} name The name of the function to inspect.
  269. * @param {Function} func The function to inspect.
  270. * @param {number} n The arity of `func`.
  271. * @returns {Function} Returns the cast function.
  272. */
  273. function castCurry(name, func, n) {
  274. return (forceCurry || (config.curry && n > 1))
  275. ? curry(func, n)
  276. : func;
  277. }
  278. /**
  279. * Casts `func` to a fixed arity function if needed.
  280. *
  281. * @private
  282. * @param {string} name The name of the function to inspect.
  283. * @param {Function} func The function to inspect.
  284. * @param {number} n The arity cap.
  285. * @returns {Function} Returns the cast function.
  286. */
  287. function castFixed(name, func, n) {
  288. if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {
  289. var data = mapping.methodSpread[name],
  290. start = data && data.start;
  291. return start === undefined ? ary(func, n) : flatSpread(func, start);
  292. }
  293. return func;
  294. }
  295. /**
  296. * Casts `func` to an rearged function if needed.
  297. *
  298. * @private
  299. * @param {string} name The name of the function to inspect.
  300. * @param {Function} func The function to inspect.
  301. * @param {number} n The arity of `func`.
  302. * @returns {Function} Returns the cast function.
  303. */
  304. function castRearg(name, func, n) {
  305. return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))
  306. ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])
  307. : func;
  308. }
  309. /**
  310. * Creates a clone of `object` by `path`.
  311. *
  312. * @private
  313. * @param {Object} object The object to clone.
  314. * @param {Array|string} path The path to clone by.
  315. * @returns {Object} Returns the cloned object.
  316. */
  317. function cloneByPath(object, path) {
  318. path = toPath(path);
  319. var index = -1,
  320. length = path.length,
  321. lastIndex = length - 1,
  322. result = clone(Object(object)),
  323. nested = result;
  324. while (nested != null && ++index < length) {
  325. var key = path[index],
  326. value = nested[key];
  327. if (value != null) {
  328. nested[path[index]] = clone(index == lastIndex ? value : Object(value));
  329. }
  330. nested = nested[key];
  331. }
  332. return result;
  333. }
  334. /**
  335. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  336. * version with conversion `options` applied.
  337. *
  338. * @param {Object} [options] The options object. See `baseConvert` for more details.
  339. * @returns {Function} Returns the converted `lodash`.
  340. */
  341. function convertLib(options) {
  342. return _.runInContext.convert(options)(undefined);
  343. }
  344. /**
  345. * Create a converter function for `func` of `name`.
  346. *
  347. * @param {string} name The name of the function to convert.
  348. * @param {Function} func The function to convert.
  349. * @returns {Function} Returns the new converter function.
  350. */
  351. function createConverter(name, func) {
  352. var realName = mapping.aliasToReal[name] || name,
  353. methodName = mapping.remap[realName] || realName,
  354. oldOptions = options;
  355. return function(options) {
  356. var newUtil = isLib ? pristine : helpers,
  357. newFunc = isLib ? pristine[methodName] : func,
  358. newOptions = assign(assign({}, oldOptions), options);
  359. return baseConvert(newUtil, realName, newFunc, newOptions);
  360. };
  361. }
  362. /**
  363. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  364. * arguments, ignoring any additional arguments.
  365. *
  366. * @private
  367. * @param {Function} func The function to cap iteratee arguments for.
  368. * @param {number} n The arity cap.
  369. * @returns {Function} Returns the new function.
  370. */
  371. function iterateeAry(func, n) {
  372. return overArg(func, function(func) {
  373. return typeof func == 'function' ? baseAry(func, n) : func;
  374. });
  375. }
  376. /**
  377. * Creates a function that wraps `func` to invoke its iteratee with arguments
  378. * arranged according to the specified `indexes` where the argument value at
  379. * the first index is provided as the first argument, the argument value at
  380. * the second index is provided as the second argument, and so on.
  381. *
  382. * @private
  383. * @param {Function} func The function to rearrange iteratee arguments for.
  384. * @param {number[]} indexes The arranged argument indexes.
  385. * @returns {Function} Returns the new function.
  386. */
  387. function iterateeRearg(func, indexes) {
  388. return overArg(func, function(func) {
  389. var n = indexes.length;
  390. return baseArity(rearg(baseAry(func, n), indexes), n);
  391. });
  392. }
  393. /**
  394. * Creates a function that invokes `func` with its first argument transformed.
  395. *
  396. * @private
  397. * @param {Function} func The function to wrap.
  398. * @param {Function} transform The argument transform.
  399. * @returns {Function} Returns the new function.
  400. */
  401. function overArg(func, transform) {
  402. return function() {
  403. var length = arguments.length;
  404. if (!length) {
  405. return func();
  406. }
  407. var args = Array(length);
  408. while (length--) {
  409. args[length] = arguments[length];
  410. }
  411. var index = config.rearg ? 0 : (length - 1);
  412. args[index] = transform(args[index]);
  413. return func.apply(undefined, args);
  414. };
  415. }
  416. /**
  417. * Creates a function that wraps `func` and applys the conversions
  418. * rules by `name`.
  419. *
  420. * @private
  421. * @param {string} name The name of the function to wrap.
  422. * @param {Function} func The function to wrap.
  423. * @returns {Function} Returns the converted function.
  424. */
  425. function wrap(name, func) {
  426. var result,
  427. realName = mapping.aliasToReal[name] || name,
  428. wrapped = func,
  429. wrapper = wrappers[realName];
  430. if (wrapper) {
  431. wrapped = wrapper(func);
  432. }
  433. else if (config.immutable) {
  434. if (mapping.mutate.array[realName]) {
  435. wrapped = wrapImmutable(func, cloneArray);
  436. }
  437. else if (mapping.mutate.object[realName]) {
  438. wrapped = wrapImmutable(func, createCloner(func));
  439. }
  440. else if (mapping.mutate.set[realName]) {
  441. wrapped = wrapImmutable(func, cloneByPath);
  442. }
  443. }
  444. each(aryMethodKeys, function(aryKey) {
  445. each(mapping.aryMethod[aryKey], function(otherName) {
  446. if (realName == otherName) {
  447. var data = mapping.methodSpread[realName],
  448. afterRearg = data && data.afterRearg;
  449. result = afterRearg
  450. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  451. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  452. result = castCap(realName, result);
  453. result = castCurry(realName, result, aryKey);
  454. return false;
  455. }
  456. });
  457. return !result;
  458. });
  459. result || (result = wrapped);
  460. if (result == func) {
  461. result = forceCurry ? curry(result, 1) : function() {
  462. return func.apply(this, arguments);
  463. };
  464. }
  465. result.convert = createConverter(realName, func);
  466. if (mapping.placeholder[realName]) {
  467. setPlaceholder = true;
  468. result.placeholder = func.placeholder = placeholder;
  469. }
  470. return result;
  471. }
  472. /*--------------------------------------------------------------------------*/
  473. if (!isObj) {
  474. return wrap(name, func);
  475. }
  476. var _ = func;
  477. // Convert methods by ary cap.
  478. var pairs = [];
  479. each(aryMethodKeys, function(aryKey) {
  480. each(mapping.aryMethod[aryKey], function(key) {
  481. var func = _[mapping.remap[key] || key];
  482. if (func) {
  483. pairs.push([key, wrap(key, func)]);
  484. }
  485. });
  486. });
  487. // Convert remaining methods.
  488. each(keys(_), function(key) {
  489. var func = _[key];
  490. if (typeof func == 'function') {
  491. var length = pairs.length;
  492. while (length--) {
  493. if (pairs[length][0] == key) {
  494. return;
  495. }
  496. }
  497. func.convert = createConverter(key, func);
  498. pairs.push([key, func]);
  499. }
  500. });
  501. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  502. each(pairs, function(pair) {
  503. _[pair[0]] = pair[1];
  504. });
  505. _.convert = convertLib;
  506. if (setPlaceholder) {
  507. _.placeholder = placeholder;
  508. }
  509. // Assign aliases.
  510. each(keys(_), function(key) {
  511. each(mapping.realToAlias[key] || [], function(alias) {
  512. _[alias] = _[key];
  513. });
  514. });
  515. return _;
  516. }
  517. module.exports = baseConvert;