LoginSignup
0
0

More than 1 year has passed since last update.

javascriptでプログレスバーを生成する関数を作る

Last updated at Posted at 2021-09-29

discordで音楽botを作成する際に今流している曲がどこまで再生されているかを出したかったので作りました。
いろいろな場所に応用が効くと思います。

追記:hn9024さんよりコメントで「進捗が0の時にバーの長さが変わる」「コードはもっと簡略化できる」とご指摘をいただきました。
コードを修正させていただきます。ありがとうございました

javascript
const getProgress = (currentPosition, endPosition, size, c0, c1, c2) => {
  const per = currentPosition / endPosition;
  const pos = Math.round((size - 1) * per);
  return `[${c1.repeat(pos)}${c0}${c2.repeat(size - pos - 1)}]`;
};

// example
const max = 20;
const size = 11;
for(let i = 0; i <= max; i++) {
  console.log(getProgress(i, max, size, "", "", ""), i);
}
/*
[☆□□□□□□□□□□] 0
[■☆□□□□□□□□□] 1
[■☆□□□□□□□□□] 2
[■■☆□□□□□□□□] 3
[■■☆□□□□□□□□] 4
[■■■☆□□□□□□□] 5
[■■■☆□□□□□□□] 6
[■■■■☆□□□□□□] 7
[■■■■☆□□□□□□] 8
[■■■■■☆□□□□□] 9
[■■■■■☆□□□□□] 10
[■■■■■■☆□□□□] 11
[■■■■■■☆□□□□] 12
[■■■■■■■☆□□□] 13
[■■■■■■■☆□□□] 14
[■■■■■■■■☆□□] 15
[■■■■■■■■☆□□] 16
[■■■■■■■■■☆□] 17
[■■■■■■■■■☆□] 18
[■■■■■■■■■■☆] 19
[■■■■■■■■■■☆] 20
*/
0
0
1

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