Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

wakamsha
October 07, 2017

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

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

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

wakamsha

October 07, 2017
Tweet

More Decks by wakamsha

Other Decks in Technology

Transcript

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

    > -1 || ua.indexOf('iPad') > -1) { return 'ios'; } else { return 'other'; } Bad Part
  2. 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Λ΋ͬͱγϯϓϧʹॻ ͚ͳ͍ͩΖ͏͔ʜʁ
  3. Bad Part ary.map(item => item * 1000); ary.map(item => {

    console.log(item); return item * 1000; });
  4. Bad Part ary.map(item => item * 1000); ary.map(item => {

    console.log(item); return item * 1000; });
  5. Bad Part ary.map(item => item * 1000); ary.map(item => {

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

    { foo = 'forenoon'; bar = 'am'; } else { foo = 'afternoon'; bar = 'pm'; } Bad Part
  7. let foo; let bar; if (new Date().getHours() < 12 )

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

    < 12 ) { return { foo: 'forenoon', bar: 'am' }; } else { return { foo: 'afternoon', bar: 'pm' } } })(); Good Part
  9. // 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]); });
  10. // 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ܕͰఆٛ͢Δ͜ͱʹͳͬͯ͠·͏ͷ͸ྑ͘ͳ͍
  11. const result = params.reduce((acc, param) => { const pair =

    param.split('='); acc[pair[0]] = decodeURIComponent(pair[1]); return acc; }, {}); Good Part
  12. 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ͱશ͘ಉ͡ ҧ͍͸໭Γ஋͕ஞ࣍ฦΔͱ͍͏఺ͷΈ