Skip to content

Commit

Permalink
Merge pull request #2694 from MadDeveloper/add-move-function
Browse files Browse the repository at this point in the history
feat(List): add move function
  • Loading branch information
CrossEye committed Nov 21, 2018
2 parents 706bd5b + f48836c commit 89f4540
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions source/index.js
Expand Up @@ -139,6 +139,7 @@ export { default as mergeWithKey } from './mergeWithKey';
export { default as min } from './min';
export { default as minBy } from './minBy';
export { default as modulo } from './modulo';
export { default as move } from './move';
export { default as multiply } from './multiply';
export { default as nAry } from './nAry';
export { default as negate } from './negate';
Expand Down
36 changes: 36 additions & 0 deletions source/move.js
@@ -0,0 +1,36 @@
import _curry3 from './internal/_curry3';

/**
* Move an item, at index `from`, to index `to`, in a list of elements.
* A new list will be created containing the new elements order.
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {Number} from The source index
* @param {Number} to The destination index
* @param {Array} list The list which will serve to realise the move
* @return {Array} The new list reordered
* @example
*
* R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f']
* R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation
*/
var move = _curry3(function(from, to, list) {
var length = list.length;
var result = list.slice();
var positiveFrom = from < 0 ? length + from : from;
var positiveTo = to < 0 ? length + to : to;
var item = result.splice(positiveFrom, 1);

return positiveFrom < 0 || positiveFrom >= list.length
|| positiveTo < 0 || positiveTo >= list.length
? list
: []
.concat(result.slice(0, positiveTo))
.concat(item)
.concat(result.slice(positiveTo, list.length));
});

export default move;
22 changes: 22 additions & 0 deletions test/move.js
@@ -0,0 +1,22 @@
var R = require('../source');
var eq = require('./shared/eq');

var list = ['a', 'b', 'c', 'd', 'e', 'f'];

describe.only('move', function() {
it('moves an element from an index to another', function() {
eq(R.move(0, 1, list), ['b', 'a', 'c', 'd', 'e', 'f']);
eq(R.move(2, 1, list), ['a', 'c', 'b', 'd', 'e', 'f']);
eq(R.move(-1, 0, list), ['f', 'a', 'b', 'c', 'd', 'e']);
eq(R.move(0, -1, list), ['b', 'c', 'd', 'e', 'f', 'a']);
});

it('does nothing when indexes are outside the list outbounds', function() {
eq(R.move(-20, 2, list), list);
eq(R.move(20, 2, list), list);
eq(R.move(2, 20, list), list);
eq(R.move(2, -20, list), list);
eq(R.move(20, 20, list), list);
eq(R.move(-20, -20, list), list);
});
});

0 comments on commit 89f4540

Please sign in to comment.