Created
March 8, 2017 00:52
-
-
Save goldhand/46786e18b6609935ed59244c538841d3 to your computer and use it in GitHub Desktop.
Immutable move item in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Immutable move item | |
*/ | |
const move = (arr, from, to) => { | |
const clone = [...arr]; | |
Array.prototype.splice.call(clone, to, 0, | |
Array.prototype.splice.call(clone, from, 1)[0] | |
); | |
return clone; | |
}; | |
/** | |
* Immutable move target a distance | |
*/ | |
const moveTarget = (arr, target, distance) => { | |
const from = arr.indexOf(target); | |
if (~from) { | |
return move(arr, from, from + distance); | |
} | |
}; | |
describe('move', () => { | |
it('can move', () => { | |
const input = [1, 2, 3, 4, 5]; | |
const expected = [1, 3, 4, 2, 5]; | |
Object.freeze(input); | |
Object.freeze(expected); | |
const actual = move(input, 1, 3); | |
expect(actual).toEqual(expected); | |
}); | |
it('can moveTarget', () => { | |
const input = [1, 2, 9, 4, 5, 6, 7]; | |
const expected = [1, 2, 4, 5, 9, 6, 7]; | |
Object.freeze(input); | |
Object.freeze(expected); | |
const actual = moveTarget(input, 9, 2); | |
expect(actual).toEqual(expected); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment