Example 1 — Lists, Objects, and Strings (Official Samples)
The same function swaps list items, object values, and characters.
const letters = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(R.swap(0, 2, letters)); // ['c', 'b', 'a', 'd', 'e', 'f']
console.log(R.swap(-1, 0, letters)); // ['f', 'b', 'c', 'd', 'e', 'a']
console.log(R.swap('a', 'b', { a: 1, b: 2 })); // { a: 2, b: 1 }
console.log(R.swap(0, 2, 'foo')); // 'oof' How It Works
- Two indexes.
'a'at 0 and'c'at 2 trade places; the rest stay put. - Negative index.
-1means the last item, so'f'and'a'swap. - Object. For objects the “indexes” are key names, so the values of
aandbswap. - String. Characters 0 and 2 of
'foo'swap and are joined back into'oof'.
