「それ、もっとスマートに書けるよ」がもっとスマートに書けるよ

  • 9
    Like
  • 1
    Comment

それ、もっとスマートに書けるよ」がもっとスマートに書けるよ。

ある特定の文字列が別の文字列内にあるかどうか

const ua = navigator.userAgent;

if (~ua.indexOf('iPhone') || ~ua.indexOf('iPod') || ~ua.indexOf('iPad')) {
  return 'ios';
} else {
  return 'other';
}

String.prototype.includes()を使いましょう。

const ua = navigator.userAgent;

if (ua.includes('iPhone') || ua.includes('iPod') || ua.includes('iPad')) {
  return 'ios';
} else {
  return 'other';
}

※「それ、もっとスマートに書けるよ」を書いた人はnavigator.userAgentを配列だと勘違いしていますが、navigator.userAgentは文字列です。(だからua.indexOf()Array.prototype.indexOf()ではなくてString.prototype.indexOf()です。)「ある特定の要素が配列内にあるかどうか」を調べる場合は、Array.prototype.includes()を使いましょう。

それ即時関数使わなくても出来るよ

const { foo, bar } = (() => {
  if (new Date().getHours() < 12) {
    return {
      foo: 'forenoon',
      bar: 'am'
    }
  } else {
    return {
      foo: 'afternoon',
      bar: 'pm'
    }
  }
})();

三項演算子を使いましょう。

const { foo, bar } =
  new Date().getHours() < 12 ?
  { foo: 'forenoon', bar: 'am' } :
  { foo: 'afternoon', bar: 'pm' }

URLクエリーパラメータのパース

const result = params.reduce((acc, param) => {
  const pair = param.split('=');
  acc[pair[0]] = decodeURIComponent(pair[1]);
  return acc;
}, {});

URLSearchParamsを使いましょう。

const result = new URLSearchParams(params);
66contribution

ある特定の文字列が別の文字列内にあるかどうか

場合によってはlist化しておいてもいいと思います。
ついでに関数化も

is_iOS.js
const is_iOS=()=>{
  const ua = navigator.userAgent;
  const ios_list=['iPhone', 'iPad', 'iPod'];
  for( const l of ios_list ) if( ua.includes(l) ) return true;
  else return false;
}

ua自体を引数にしても良いかもしれません。