We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
/** * @arr: {Array} 操作数组 * @startPos: {Number} 需要移动数据开始项 * @length: {Number} 需要移动数据项数 * @moveSteps: {Number} 需要移动位数, positive number move right, minus number move left * @return {Array} * */ const moveArrayItem = (arr, startPos, length, moveSteps) => { if (!(arr instanceof Array)) { throw new Error(`arr can only be: Array, got:${Object.prototype.toString.call(arr)}`) } if (typeof startPos !== 'number') { if (startPos < 0) { throw new Error(`startPos can only be: positive integer, got:${startPos}`) } if (startPos.toString().indexOf('.') !== -1) { throw new Error(`startPos can only be: positive integer, got:${startPos}`) } throw new Error(`startPos can only be: Number, got:${startPos}`) } if (typeof length !== 'number') { if (length < 0) { throw new Error(`length can only be: positive integer, got:${length}`) } if (length.toString().indexOf('.') !== -1) { throw new Error(`startPos can only be: positive integer, got:${length}`) } throw new Error(`length can only be: Number, got:${length}`) } if (typeof moveSteps !== 'number') { throw new Error(`moveSteps can only be: Number, got:${length}`) } const originArrLen = arr.length const moveItems = arr.splice(startPos, length) || [] if (moveSteps < 0) { moveSteps = Math.abs(moveSteps) arr.splice(startPos - moveSteps >= 0 ? startPos - moveSteps : 0, 0, ...moveItems) } else { arr.splice(startPos + moveSteps <= originArrLen - 1 ? startPos + moveSteps : originArrLen - 1, 0, ...moveItems) } return arr } // example const arr = [1, 2, 3, 4, 5, 6, 7] console.log(`move: ${arr}`, moveArrayItem(arr, 1, 2, 1)) // [1, 4, 2, 3, 5, 6, 7]
The text was updated successfully, but these errors were encountered:
No branches or pull requests
The text was updated successfully, but these errors were encountered: