자바스크립트 코딩테스트 연습 8일차

Y·2020년 8월 8일
0

문제


내풀이


// TODO: complete this object/class

// The constructor takes in an array of items and a integer indicating how many
// items fit within a single page
function PaginationHelper(collection, itemsPerPage){
  this.collection = collection;
  this.itemsPerPage = itemsPerPage;
  
}

// returns the number of items within the entire collection
PaginationHelper.prototype.itemCount = function() {
  return this.collection.length;
}

// returns the number of pages
PaginationHelper.prototype.pageCount = function() {
  return parseInt(this.collection.length/this.itemsPerPage) + 1;
}

// returns the number of items on the current page. page_index is zero based.
// this method should return -1 for pageIndex values that are out of range
PaginationHelper.prototype.pageItemCount = function(pageIndex) {
  if(pageIndex > parseInt(this.collection.length/this.itemsPerPage)){
    return -1
  } else if(pageIndex === parseInt(this.collection.length/this.itemsPerPage)) {
    return this.collection.length % this.itemsPerPage;
  } else {
    return this.itemsPerPage;
  }
}


// determines what page an item is on. Zero based indexes
// this method should return -1 for itemIndex values that are out of range
PaginationHelper.prototype.pageIndex = function(itemIndex) {
  if(this.collection[itemIndex] !== undefined){
    return parseInt(itemIndex/this.itemsPerPage)
  } else {
    return -1
  }
}

우선, 메서드를 만들어주는 문제기 때문에, 메서드를 호출한 함수인 PaginationHelper 에 변수를 선언했다. 내부 메서드에 쓰이는 this는 호출 함수 객체에 바인딩된다.

추천 풀이


function PaginationHelper(collection, itemsPerPage){
  this.collection = collection, this.itemsPerPage = itemsPerPage;
}

PaginationHelper.prototype.itemCount = function() {
  return this.collection.length;
}

PaginationHelper.prototype.pageCount = function() {
  return Math.ceil(this.collection.length / this.itemsPerPage);
}

PaginationHelper.prototype.pageItemCount = function(pageIndex) {
  return pageIndex < this.pageCount() 
    ? Math.min(this.itemsPerPage, this.collection.length - pageIndex * this.itemsPerPage)
    : -1;
}

PaginationHelper.prototype.pageIndex = function(itemIndex) {
  return itemIndex < this.collection.length && itemIndex >= 0
    ? Math.floor(itemIndex / this.itemsPerPage)
    : -1;
}

공부


메서드를 추가할 때, 메서드 정의가 끝난시점에서의 해당 메서드는 this인자로 메서드도 사용할 수 있다는걸 다시 깨닫게 했다. 내가 작성하는 시점에서 함수가 돌아가는것이아니라, 메서드 함수는 정의가 끝난후에 PaginationHelper의 메서드로 전부 저장되고 호출에 따라 내부프로퍼티의 함수들이 실행되기 때문에 함수객체 내부의 프로퍼티는 모두 this인자로 사용할 수 있었던 것 같다. 아직 함수에 대해 공부를 더 해야할 것 같다. 내 코드엔 불필요한 코드들이 많이 들어간 셈이다.. 또한 삼항연산자로 코드를 보다 간결화 하는 테크닉을 길러야겠다.

profile
연세대학교 산업공학과 웹개발 JavaScript

0개의 댓글