source: node_modules/ramda/es/swap.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 2.5 KB
RevLine 
[d24f17c]1import _curry3 from "./internal/_curry3.js";
2import _isArray from "./internal/_isArray.js";
3import _isString from "./internal/_isString.js";
4import clone from "./clone.js";
5
6var swapObject = function (indexA, indexB, o) {
7 var copy = clone(o);
8 var properties = Object.getOwnPropertyNames(copy);
9
10 if (properties.includes(indexA) && properties.includes(indexB)) {
11 var tmp = copy[indexA];
12 copy[indexA] = copy[indexB];
13 copy[indexB] = tmp;
14 }
15
16 return copy;
17};
18
19var swapList = function (indexA, indexB, list) {
20 var length = list.length;
21 var result = list.slice();
22 var positiveIndexA = indexA < 0 ? length + indexA : indexA;
23 var positiveIndexB = indexB < 0 ? length + indexB : indexB;
24 var positiveMin = Math.min(positiveIndexA, positiveIndexB);
25 var positiveMax = Math.max(positiveIndexA, positiveIndexB);
26
27 if (positiveIndexA < 0 || positiveIndexA > length) {
28 return result;
29 }
30
31 if (positiveIndexB < 0 || positiveIndexB > length) {
32 return result;
33 }
34
35 if (positiveIndexA === positiveIndexB) {
36 return result;
37 }
38
39 result = [].concat(result.slice(0, positiveMin)).concat([result[positiveMax]]).concat(result.slice(positiveMin + 1, positiveMax)).concat([result[positiveMin]]).concat(result.slice(positiveMax + 1, length));
40 return result;
41};
42
43var swapString = function (indexA, indexB, s) {
44 var result = swapList(indexA, indexB, s);
45 return _isArray(result) ? result.join('') : result;
46};
47/**
48 * Swap an item, at index `indexA` with another item, at index `indexB`, in an object or a list of elements.
49 * A new result will be created containing the new elements order.
50 *
51 * @func
52 * @memberOf R
53 * @since v0.29.0
54 * @category List
55 * @sig Number -> Number -> [a] -> [a]
56 * @param {Number|string|Object} indexA The first index
57 * @param {Number|string|Object} indexB The second index
58 * @param {Array|Object} o Either the object or list which will serve to realise the swap
59 * @return {Array|Object} The new object or list reordered
60 * @example
61 *
62 * R.swap(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['c', 'b', 'a', 'd', 'e', 'f']
63 * R.swap(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'b', 'c', 'd', 'e', 'a']
64 * R.swap('a', 'b', {a: 1, b: 2}); //=> {a: 2, b: 1}
65 * R.swap(0, 2, 'foo'); //=> 'oof'
66 */
67
68
69var swap =
70/*#__PURE__*/
71_curry3(function (indexA, indexB, o) {
72 if (_isArray(o)) {
73 return swapList(indexA, indexB, o);
74 } else if (_isString(o)) {
75 return swapString(indexA, indexB, o);
76 } else {
77 return swapObject(indexA, indexB, o);
78 }
79});
80
81export default swap;
Note: See TracBrowser for help on using the repository browser.