Skip to content
New issue

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

数组项前移后移(用于排序) #10

Open
54leibo opened this issue Mar 17, 2020 · 0 comments
Open

数组项前移后移(用于排序) #10

54leibo opened this issue Mar 17, 2020 · 0 comments

Comments

@54leibo
Copy link
Owner

54leibo commented Mar 17, 2020

/**
 * @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]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant