LoginSignup
0

More than 5 years have passed since last update.

Listの要素の並び替えをImmutable.jsを使ってシンプルに書く話

Last updated at Posted at 2016-12-16

この記事はOpt Technologies Advent Calendar 2016の15日目です。
(色々手が回っておらず、ちょっとしたポエム的な記事になります、ご容赦ください。。。)

問題

Drag & Dropでlistの順番を並び替えるUIをよく見かけると思います。
このとき、選択した要素をlist内で別のindexに格納するものを、これまでこのように書いていました。

before
fucntion exchangeSortList<T>(targetList: T[], sourceId: number, targetId: number): T[] {
  return sourceId < targetId ?
    [...targetList.slice(0, sourceId), ...targetList.slice(sourceId+1, targetId+1), targetList[sourceId], ...targetList.slice(targetId+1, targetList.length)] :
    [...targetList.slice(0, targetId), targetList[sourceId], ...targetList.slice(targetId, sourceId), ...targetList.slice(sourceId+1, targetList.length)];

正直exchangeSortListと書かれていても何をやっているのかよくわかりませんね。。。
これは、Immutable.jsの力を借りればこのように書けます。

after
fucntion exchangeSortList<T>(targetList: Immutable.List<T>, sourceId: number, targetId: number): Immutable.List<T> {
  const target = targetList.get(sourceId);
  return targetList.remove(sourceId).insert(targetId, target);

記述量も少ないし、何をやっているか一目瞭然かと思います。

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