본문 바로가기

이번주 학교 시간표

[underscore.js] useful javascript library(1)

frontend engineer는 아니지만 그동안 사용해 왔던 자바스크립트 라이브러리 중에 가장 유용하게 사용해 왔던

undercore.js를 '이번주 학교 시간표' 서비스에서도 사용하게 되었다.

 

https://underscorejs.org/

 

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive

underscorejs.org

되도록이면 최소한으로 개발을 하려고 했었기 때문에 추가적인 라이브러리를 사용을 고민했었는데

underscore.js가 없었으면 아마도 프런트 코드가 훨씬 더 복잡해져서 나중에 왜 이렇게 했을까하는 코드가 될거라 생각하면서

이 정도는 사용해도 무방하리라 합리화를 하고 사용하기로 결정.

 

Collection, Array, Object, Function 등을 지원하기 위한 다양한 유틸리티가 포함되어 있으며,

내 경우에는 SPA(Single Page Application)으로 개발을 하다보니 Object를 핸들링해야 하는 일들이 많아

Object 관련 기능들을 많이 사용하게 됐다.

 

대표적으로 시간표를 조회하는 API 응답값에서

  • 요일별 교시별 과목정보를 추출해야 하여 하나의 Object를 만들고
  • 교시별 Object를 배열로 만들어야 했었는데

예를 들어

월요일 1교시, 화요일 1교시...금요일 1교시를 하나의 Object로 만들고

월요일 2교시 화요일 2교시...금요일 2교시를 또 다른 Object로 만들고....해서 이 Object들의 Array를 만들어야 했다.

 

생각만 해도 복잡한 코드들을 underscore를 사용하면 간단히 구현이 가능하다.

for (var inx = 1; inx < 16; inx++) {
	var monday = getMondayOfThisWeek();
					
	var mon = _.where(result, {PERIO: inx.toString(), ALL_TI_YMD: monday.toString()}),
		tue = _.where(result, {PERIO: inx.toString(), ALL_TI_YMD: (monday++).toString()}),
		wed = _.where(result, {PERIO: inx.toString(), ALL_TI_YMD: (monday++).toString()}),
		thu = _.where(result, {PERIO: inx.toString(), ALL_TI_YMD: (monday++).toString()}),
		fri = _.where(result, {PERIO: inx.toString(), ALL_TI_YMD: (monday++).toString()});
                
	if (_.isEmpty(mon) && _.isEmpty(tue) && _.isEmpty(wed) && _.isEmpty(thu) && _.isEmpty(fri)) {
    	break;
	}
    subjects.push({
    	PERIO: inx,
    	MON: !_.isEmpty(mon) ? mon[0] : null,
    	TUE: !_.isEmpty(tue) ? tue[0] : null,
    	WED: !_.isEmpty(wed) ? wed[0] : null,
    	THU: !_.isEmpty(thu) ? thu[0] : null,
    	FRI: !_.isEmpty(fri) ? fri[0] : null
    });
}

여기서 사용한 where 함수의 경우, 

첫번째 파라미터 Object 리스트에서

두번째 파라미터 속성값을 갖는 Object들의 배열을 반환해 준다.

 

아래는 unsdercore.js 페이지에 소개된 where의 간단한 예시이다.

_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611}, {title: "The Tempest", author: "Shakespeare", year: 1611}]