본문 바로가기
javaScript

javaScript - 프로세싱 코드모음

by sinabeuro 2021. 8. 4.
728x90

 

Object.entries와 구조분해 할당 연습

const cartItems = [
  { id: 1, item: '핸드밀', price: 40000, discount: 0 },
  { id: 2, item: 'A4용지', price: 4000, discount: 0 },
  { id: 3, item: '수영복', price: 120000, discount: 0 },
  { id: 4, item: '색연필72색', price: 150000, discount: 0 },
];

const extractValueInObject = (obj) => Object
  .entries(obj)
  .map(([, value]) => String(value));	// 구조분해 할당 기법

const cartItemsString = cartItems
  .map(extractValueInObject)
  .join('===');

console.log(cartItemsString);	// 1,핸드밀,40000,0===2,A4용지,4000,0===3,수영복,120000,0===4,색연필72색,150000,0

 

 

문자열을 카멜 표기법으로 변환

// 카멜식 변환 코드
function simpleCamelCase(text) {
  var res = text.split(' ')
    .map((word, wordIdx) => word.split('')
         .map((char, charIdx) => (wordIdx>0 && charIdx===0)?char.toUpperCase():char.toLowerCase())
         .join('')
    ).join('')
  
  return res;
}

console.log(simpleCamelCase('Hong gil dong'));	// hongGilDong

 

 

백틱 활용 - 백틱 내부에 수식 또는 함수로 연산가능, restParam 활용

function div(strings, ...fns) {
  console.log(strings);
  console.log(fns);
  const flat = s => s.split('\n').join('');
  
  return function(props) {
    return `<div style="${flat(strings[0]) + (fns[0] && fns[0](props)) + flat(strings[1])}"></div>`;
  }
}
  
const Div = div`
  font-size: 20px;
  color: ${props => props.active ? 'white' : 'gray' };
  border: none;
`;
  
console.log(Div({ active: true }));
console.log(Div({ }));
// handlebars 활용에 유용함

Template Literals은 함수에 파라미터를 넘길 때 문자열로 넘겨주는 기법입니다.

Tagged Template은 Template Literals로 문자열 파라미터를 넘길 때 ${ } 보간법으로 파라미터 넣는 방식을 말합니다. 

function div(strings, ...fns) { } 예제에서 strings은 문자열로 받은 Template Literals 변수를 Tagged Template 기준으로 배열로 받게 됩니다.

반면 fns파라미터는 ${ } 보간법으로 넘겨준 Tagged Template 변수를 배열로 받습니다.

 

 

 

객체 그룹핑예제

const sourceObject = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5,
};

const groupInfo = {
  aGroup: ['a', 'b'],
  bGroup: ['c', 'd', 'e']
};

function makeGroup(source, info) {
  const merge = (a, b) => ({...a, ...b});
  
  return Object.keys(info)
    .map(group => ({ [group]: info[group]
      .map(k => ({ [k]: source[k] }))
      .reduce(merge, {})
    }))
    .reduce(merge, {});
}

console.log(
  makeGroup(sourceObject, groupInfo);
);

reduce의 첫 인자는 누적된 데이터이고 두번째 인자는 현재 객체입니다.

 

 

특정 키를 그룹으로 묶어서 분류한 예제

const sourceObject = [
  {tempNo: 1001, name: 'test1', serialNm: 'A001'},
  {tempNo: 1001, name: 'test2', serialNm: 'A002'},
  {tempNo: 1002, name: 'test3', serialNm: 'B001'},
  {tempNo: 1002, name: 'test4', serialNm: 'B002'},
  {tempNo: 1001, name: 'test5', serialNm: 'A003'},
];

function makeGroup(arr) {
  return arr.reduce((acc, cur, idx) {
    if(acc.indexOf(cur.tempNo) < 0) {
      acc.push(cur.tempNo);
    }
    return acc;
  }, [])
  .map(item => ({ [item]: arr.reduce((a, b) => {
      if(b.tempNo === item) {
          a.push(b);
      }
      return a;
    }, [])
  }));  
}

console.log(makeGroup(sourceObject));

 

 

클래스에서 2차원 배열을 이용한 객체 배열 만들기 예제

const movieData = `Title,Release,Ticketing Rate,Director
보헤미안 렙소디,2018.10.31,11.5%,브라이언 싱어
완벽한 타인,2018.10.31,4.6%,이재규
동네사람들,2018.11.07,0.5%,임진순`;

class HeaderListData {
  constructor(source, separator = ',') {
    const rawData = source.split('\n');
    
    this.headers = rawData[0].split(separator);
    this.rows = rawData
                  .filter((row, index) => index > 0)
                  .map(row => row.split(separator));
  	// rows는 배열로 만듭니다.
  }
  
  row = index => this.rows[index]
    .map((row, index) => [this.headers[index], row]);
  // rows를 2차원 배열로 만듭니다. 2차수 배열은 [헤더명, row데이터] 구조를 갖게 됩니다.
  
  get length() {
    return this.rows.length;
  }
  
  get columnLength() {
    return this.headers.length;
  }

}

class MakeObject extends HeaderListData {
  toObject = index => this
    .row(index)
    .reduce((a, [key, value]) => ({...a, [key]: value}), {});
  // 2차원 배열의 2차수를 없애고 1차원 객체배열 형태로 만들어줍니다. 첨부 이미지 참조
  
  toAllObject = () => 
    Array(this.length)
      .fill(0)
      .map((item, index) => this.toObject(index))
  // 배열 메소드를 쓰기위해 Array로 빈 배열을 만들고 fill(0)으로 데이터를 채움
}

const movieList = new MakeObject(movieData);

console.log(movieList.toAllObject());

rows[0]데이터를 toObject 함수 실행하여 나타낸 결과

문자열을 split하여 배열을 만듭니다.

rows 배열을 이차원 배열로 만듭니다.

rows 배열의 2차수 배열을 객체를 합쳐 1차원 객체 배열로 만듭니다.

1차원 객체배열들을 합쳐서 최종 완성된 객체배열을 만듭니다.

728x90

댓글