LoginSignup
0
0

More than 5 years have passed since last update.

TypeScript 配列の要素を入れ替える関数

Last updated at Posted at 2018-02-04

配列の何番目の要素と何番目の要素を入れ替えるみたいな処理をしたかったんだけど、これっていうのが探しても見つからなかったから自分で書いた。稀に良く使いまわしそう。
immutable.js にはきっとこういう機能が含まれてるはず。
Spread演算子を使うとconcatが可読性高く書けていいなと思いました。

Demo: https://jsfiddle.net/kmdsbng/ropb6867/

const swapArray = <P>(ary: P[], index1: number, index2: number): P[] => {
  const [frontIndex, backIndex] =
    (index1 < index2) ? [index1, index2] : [index2, index1];

  if (frontIndex < 0 || ary.length <= backIndex) {
      throw new RangeError();
  }

  if (frontIndex == backIndex) {
      return ary;
  }

  const frontValue = ary[frontIndex]
  const backValue = ary[backIndex]
  const frontward = ary.slice(0, frontIndex)
  const middle = ary.slice(frontIndex + 1, backIndex)
  const backward = ary.slice(backIndex + 1, ary.length)

  return [
      ...frontward,
      backValue,
      ...middle,
      frontValue,
      ...backward]
}

const ary = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

console.log(swapArray(ary, 2, 5)); // [0, 1, 5, 3, 4, 2, 6, 7, 8, 9, 10, 11]
console.log(swapArray(ary, 0, 0)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
console.log(swapArray(ary, 10, 11)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10]
console.log(swapArray(ary, 11, 0)); // [11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]
//console.log(swapArray(ary, 10, 12)); // RangeError
//console.log(swapArray(ary, -1, 1)); // RangeError
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0