それ、もっとスマートに書けるよ - JavaScript コードをもっと短く、もっとシンプルに書く Tips 4選

82ed567f8497acfed7f7b464225dd536?s=47 wakamsha
October 07, 2017

それ、もっとスマートに書けるよ - JavaScript コードをもっと短く、もっとシンプルに書く Tips 4選

2017年10月6日『まぼろしのJS勉強会 #1 「ナウいJSの書き方・考え方」』にて発表した資料です。

https://maboroshi.connpass.com/event/66502/
#mbrs_js_study

82ed567f8497acfed7f7b464225dd536?s=128

wakamsha

October 07, 2017
Tweet

Transcript

  1. 1.
  2. 6.

    const ua = navigator.userAgent; if (ua.indexOf('iPhone') > -1 || ua.indexOf('iPod')

    > -1 || ua.indexOf('iPad') > -1) { return 'ios'; } else { return 'other'; } Bad Part
  3. 7.

    const ua = navigator.userAgent; if (ua.indexOf('iPhone') > -1 || ua.indexOf('iPod')

    > -1 || ua.indexOf('iPad') > -1) { return 'ios'; } else { return 'other'; } Bad Part ͦͷ··ͩͱ࢖͍ʹ͍͘ ഑ྻͷઌ಄ʹ஋͕͋Δͱ໭Γ஋͕0ͳͷͰfalseͱͳΓɺ஋͕ແ͍ͱ-1ͳͷ Ͱtrueͱͳͬͯ͠·͏ ୯७ʹ஋͕͋Δ͔Ͳ͏͔Λ஌Γ͍͚ͨͩͳͷͰɺ > -1Λ΋ͬͱγϯϓϧʹॻ ͚ͳ͍ͩΖ͏͔ʜʁ
  4. 13.

    Bad Part ary.map(item => item * 1000); ary.map(item => {

    console.log(item); return item * 1000; });
  5. 14.

    Bad Part ary.map(item => item * 1000); ary.map(item => {

    console.log(item); return item * 1000; });
  6. 15.

    Bad Part ary.map(item => item * 1000); ary.map(item => {

    console.log(item); return item * 1000; }); ͔ͤͬ͘ͷϫϯϥΠφʔ่͕Εͯ͠·͏ Ұ࣌తͳconsole.logͷͨΊʹϒϩοΫԽ͢ΔͳͲؔ਺ͷߏ଄Λม͑ͳͯ͘ ͸ͳΒͳ͍
  7. 21.

    let foo; let bar; if (new Date().getHours() < 12 )

    { foo = 'forenoon'; bar = 'am'; } else { foo = 'afternoon'; bar = 'pm'; } Bad Part
  8. 22.

    let foo; let bar; if (new Date().getHours() < 12 )

    { foo = 'forenoon'; bar = 'am'; } else { foo = 'afternoon'; bar = 'pm'; } Bad Part ίʔυ͕ංେԽ͢ΔʹͭΕͯlet͸ՄಡੑΛଛͳ͏ ม਺એݴ͸constΛ࢖͍ɺlet͸ۃྗ߇͑Δͷ͕๬·͍͠ ͦΕlet࢖Θͳͯ͘΋ग़དྷΔΑ
  9. 25.

    const {foo, bar} = (() => { if (new Date().getHours()

    < 12 ) { return { foo: 'forenoon', bar: 'am' }; } else { return { foo: 'afternoon', bar: 'pm' } } })(); Good Part
  10. 29.

    // https://example.com/?utm_s=google&utm_m=ppc&utm_c=campaign1 const params = location.search.substring(1).split('&'); Bad Part const result

    = {}; params.forEach(param => { const pair = param.split('='); result[pair[0]] = decodeURIComponent(pair[1]); });
  11. 30.

    // https://example.com/?utm_s=google&utm_m=ppc&utm_c=campaign1 const params = location.search.substring(1).split('&'); Bad Part const result

    = {}; params.forEach(param => { const pair = param.split('='); result[pair[0]] = decodeURIComponent(pair[1]); }); ͍Ζ͍Ζͱ৑௕͗͢Δ ࠷ॳʹۭΦϒδΣΫτΛॳظ஋ͱͯ͠ఆٛ͠ɺϧʔϓॲཧ಺Ͱ஋Λ٧Ί͍͔ͯͳ ͯ͘͸ͳΒͳ͍ 5ZQF4DSJQUͩͱresult͸anyܕͰఆٛ͢Δ͜ͱʹͳͬͯ͠·͏ͷ͸ྑ͘ͳ͍
  12. 33.

    const result = params.reduce((acc, param) => { const pair =

    param.split('='); acc[pair[0]] = decodeURIComponent(pair[1]); return acc; }, {}); Good Part
  13. 34.

    const result = params.reduce((acc, param) => { const pair =

    param.split('='); acc[pair[0]] = decodeURIComponent(pair[1]); return acc; }, {}); Good Part ϧʔϓॲཧͷ్தஈ֊ͷ஋΋ஞ࣍ཉ͍͠ͱ͖͸ɺ3Y+4ͷscanΛ࢖͑͹0, ॻ͖ํ͸reduceͱશ͘ಉ͡ ҧ͍͸໭Γ஋͕ஞ࣍ฦΔͱ͍͏఺ͷΈ
  14. 38.