Skip to content

Latest commit

 

History

History
executable file
·
342 lines (280 loc) · 7.28 KB

3. template literal.md

File metadata and controls

executable file
·
342 lines (280 loc) · 7.28 KB

3. template literal

3-1. 소개

console.log(`a
bb
ccc`)
const a = 10
const b = 20
const str = `${a} + ${b} = ${ a + b }`
console.log(str)

3-2. 상세

1) backtick (`)

2) multi-line

3) string interpolation

3-3. Details

1) multi-line의 경우 들여쓰기에 주의

  • 들여쓰기도 문자로 인식하기 때문에 조심해야 함
const f = function () {
  const a = `abc
  def
  ghij`
  console.log(a)
}
f()

2) ${ } 내에는 또는 이 올 수 있다.

const counter = {
  current: 0,
  step: 1,
  count: function() { return this.current += this.step },
  reset: function() { return this.current = 0 }
}
console.log(`${counter.count()} ${counter.count()}
${counter.reset()} $${counter.count()}
${counter.count()}$`)

3) 결국 문자열이므로, 자동으로 toString 처리가 된다.

console.log(`${[0, 1, 2]}`)
console.log(`${{a:1, b:2}}`)
console.log(`${function(){ return 1 }}`)
console.log(`${(() => 1 )()}` + 1)

4) 중첩된 backtick 처리

console.log(`Foo ${`Bar`}`)
console.log(`Foo ${`Bar ${`Baz`}`}`)

5) 가독성을 위해 trim 처리

function a () {
  return `
<div>
    <h1>Lorem ipsum.</h1>
</div>
  `.trim()
}
console.log(a())
console.log(a().replace(/\n/g, ''))
const linesToHTML = function (characters) {
  return characters.reduce(function (charactersResult, character) {
    let {name, lines} = character
    return `${charactersResult || ''}
<article>
  <h1>${name}</h1>
  <ul>
    ${lines.reduce(function (linesResult, line) {
      return `${linesResult || ''}
    <li>${line}</li>
      `.trim()}, 0)}
  </ul>
</article>
  `.trim()}, 0)
}
const characters = [{
  name: 'Aria Stark',
  lines: ['A girl has no name.']
}, {
  name: 'John Snow',
  lines: [
    'You know nothing, John Snow.',
    'Winter is coming.'
  ]
}]
document.body.innerHTML = linesToHTML(characters)

번외 - forEach, map, reduce

1) forEach

MDN - Array.prototype.forEach

Array.prototype.forEach(callback[, thisArg])

  • callback: function (currentValue[, index[, originalArray]])
    • currentValue: 현재값
    • index: 현재 인덱스
    • originalArray: 원본 배열
  • thisArg: this에 할당할 대상. 생략시 global객체
const a = [ 1, 2, 3 ]
a.forEach(function (v, i, arr) {
    console.log(v, i, arr, this)
}, [ 10, 11, 12 ])

2) map

MDN - Array.prototype.map

Array.prototype.map(callback[, thisArg])

  • callback: function (currentValue[, index[, originalArray]])
    • currentValue: 현재값
    • index: 현재 인덱스
    • originalArray: 원본 배열
  • thisArg: this에 할당할 대상. 생략시 global객체
const a = [ 1, 2, 3 ]
const b = a.map(function (v, i, arr) {
    console.log(v, i, arr, this)
    return this[0] + v
}, [ 10 ])

3) reduce

MDN - Array.prototype.reduce

Array.prototype.reduce(callback[, initialValue])

  • initialValue: 초기값. 생략시 첫번째 인자가 자동 지정되며,
    이 경우 currentValue는 두번째 인자부터 배정된다.
  • callback: function (accumulator, currentValue[, currentIndex[, originalArray]])
    • accumulator: 누적된 계산값
    • currentValue: 현재값
    • currentIndex: 현재 인덱스
    • originalArray: 원본 배열
const arr = [ 1, 2, 3 ]
const res = arr.reduce(function (p, c, i, arr) {
  console.log(p, c, i, arr, this)
  return p + c
}, 10)
const arr = [ 1, 2, 3, 4 ]
const str = arr.reduce(function (res, item, index, array) {
  return res + item
}, '')
console.log(str)
step res item index array
1 '' 1 0 [1,2,3,4]
2 '1' 2 1 [1,2,3,4]
3 '12' 3 2 [1,2,3,4]
4 '123' 4 3 [1,2,3,4]
result '1234'
const arr = [ 'a', 'b', 'c', 'd' ]
const str = arr.reduce(function (res, item, index, array) {
  return res + item
})
console.log(str)
step res item index array
1 'a' 'b' 1 ['a','b','c','d']
2 'ab' 'c' 2 ['a','b','c','d']
3 'abc' 'd' 3 ['a','b','c','d']
result 'abcd'
const arr = [ 10, 20, 30, 40, 50 ]
const r = arr.reduce(function (p, c) {
  return p + c
})
console.log(r)
const arr = [ 10, 20, 30, 40, 50 ]
const r = arr.reduce((p, c) => p + c)
console.log(r)

3-4. template tag function

const tag = function (strs, arg1, arg2) {
  return {strs: strs, args: [arg1, arg2]}
}
const res = tag `순서가 ${1}이렇게 ${2}`
console.log(res)
const tags = function (strings, ...expressions) {
  console.log(strings, expressions)
}
const a = 'iu', b = 'Friday'
const str = tags `Hello, ${a}! Today is ${b}!!`
// ["Hello, ", "! Today is ", "!!"]
// ["iu", "Friday"]

1) expression의 수는 언제나 string의 수보다 하나 적다!

const tags = function (strs, ...exps) {
  return { strs, exps }
}
console.log(tags `${10}${20}`)
console.log(tags `a${30}`)
console.log(tags `${40}b`)

2) 이를 이용하면 strings 또는 expressions 중 하나를 순회하여 별도의 처리가 가능하다.

const addSuffix = function (strs, ...exps) {
  return strs.reduce(function (acc, curr, i) {
    let res = acc + curr + '_suffix '
    if(exps[i]) res += exps[i]
    return res
  }, '')
}
console.log(addSuffix `이 함수는${'각 문자열'}마다${'|_suffix|'}라는 글자를 추가합니다.`)

3) examples

const setDecimalSeperators = function (strs, ...args) {
  return args.reduce(function (p, c, i) {
    return p + strs[i] + (c + '').replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, '$&,')
  }, '') + strs[strs.length - 1]
}
const res = setDecimalSeperators `이 사과는 하나에 ${2000}원이고, 총 ${1234567}개를 구입하시면 총 ${2000 * 1234567}원 이에요.`
console.log(res)
const createCollection = {
  Map(keys, ...vals){
    const m = new Map()
    vals.forEach(function (val, i) {
      m.set(keys[i].trim(), val)
    })
    return m
  },
  WMap(keys, ...vals){
    const wm = new WeakMap()
    for (let i = 0 ; i < vals.length ; i+=2) {
      wm.set(vals[i], vals[i+1])
    }
    return wm
  },
}

const wkeys = [ {a : 100}, {b : 200} ]
const map = createCollection.Map `
  a ${10}
  b ${'what'}
  fn ${v => v + 10}`
let wmap = createCollection.WMap `
  ${wkeys[0]} ${10}
  ${wkeys[1]} ${20}`
console.log(map)
console.log(wmap)

3-5. String.raw

  • String.raw 를 태그함수로 사용할 경우 공백, 탭, 줄바꿈 문자를 원본으로 바꿔 출력해준다.
  • \n, \t, \r 등등 
const tag = function (strs, ...args){
  return {strs: strs, args}
}

const res1 = tag`순서가 ${1}이렇게 ${2}

`
console.log(res1);

const res2 = tag`순서가 ${1}이렇게 ${2}\n\n`
console.log(res2);

const res3 = String.raw `순서가 ${1}이렇게 ${2}\n\n`
console.log(res3);

console.log(`Hello\nWorld!`)
console.log(String.raw `Hello\nWorld!`)
console.log(String.raw `Hello
World!`)
const tags = function (strs, ...exps) {
  return { strs, exps }
}
const a = 'iu', b = 'Friday'
const str = tags `Hello, ${a}\n Today is ${b}\n`