레이블이 Javascript인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Javascript인 게시물을 표시합니다. 모든 게시물 표시

2018년 7월 15일 일요일

매 초마다 현재 시간을 표시하는 프로그램

명령형


setInterval(logClockTime, 1000);

function logClockTime(){
 
  var time = getClockTime();
 
  console.clear();
  console.log(time);
 
}
 
function getClockTime(){
 
  // 현재 시각을 얻는다.
  var date = new Date();
  var time = "";
 
  //시각을 직렬화 한다.
  var time ={
    hours : date.getHours(),
    minutes : date.getMinutes(),
    seconds: date.getSeconds(),
    ampm: "AM"
  };
 
  //상용시로 변환한다.
  if(time.hours ==12){
    time.ampm = "PM";
  }else if ( time.hours > 12){
    time.ampm = "PM";
    time.hour -= 12;
  }
 
  //시간을 2글자로 만들기 위해 앞에 0을 붙인다.
  if(time.hours <10){
    time.hours = "0" + time.hours;
  }
 
  //분을 2글자로 만들기 위해 앞에 0을 붙인다.
  if(time.minutes < 10){
    time.hours = "0"+ time.minutes;
   
  }
  //초를 2글자로 만들기 위해 앞에0을 붙인다.
  if(time.seconds <10){
    time.seconds  = "0" + time.seconds;
  }
 
 
  //" hh:mm:ss tt " 형식의 문자열을 만든다.
  return time.hours + ":"
          +time.minutes+":"
          +time.seconds + " "
          +time.ampm;
}



선언형

const abstractClockTime = date => ({
  hours: date.getHours(),
  minutes: date.getMinutes(),
  seconds: date.getSeconds()
})
 
 const civilianHours = clockTime => ({
   ...clockTime,
   hours: (clockTime.hours > 12)? clockTime.hours - 12: clockTime.hours
 })

 const appendAMPM = clockTime => ({
   ...clockTime,
   ampm: (clockTime.hours >= 12 ) ? "PM":"AM"
 })

 const display = target => time => target(time)
 const formatClock = format => time => format.replace("hh", time.hours)
 .replace("mm", time.minutes)
 .replace("ss", time.seconds)
 .replace("tt", time.ampm)

 const prependZero = key => clockTime =>
     ({
       ...clockTime,
       [key]:(clockTime[key] < 10)? "0" + clockTime[key]:clockTime[key]
     })

 const convertToCivilianTime = clockTime =>
     compose(appendAMPM, civilianHours)(clockTime)
 const doubleDigits = civilianTime =>
     compose(
       prependZero("hours"),
       prependZero("minutes"),
       prependZero("seconds")
     
     )(civilianTime)

 const startTicking =() =>
     setInterval(
       compose(
         clear,
         getCurrentTime,
         abstractClockTime,
         convertToCivilianTime,
         doubleDigits,
         formatClock("hh:mm:ss tt"),
         display(log)
       ),
       oneSecond()
     )

startTicking()

2017년 5월 17일 수요일

typescript 배워보기

function Persion(name){
this.name = name;
this.sayHi = function(){


        //var that = this; 해결방법

//새로운 스코프
setTimeout(function(){
console.log('hello my name is ' + this.name)  //that.name으로 변경
},1000)
}
}

const person = new Person('bob');


person.sayHi()

실행시 익명함수의 this가 글로벌 객체(윈도우객체)를 가르키게되어 아무것도 표시하지 않는다.



fat arrow function을 사용하면 이런 문제를 방지할수있다.

setTimeout(() => {
console.log('hello my name is ' + this.name)
}



참조 : 유튜브  https://www.youtube.com/watch?v=O0tGVx3QQYE

2017년 3월 12일 일요일

자바스크립트 프로그래밍 입문

다시 자바스크립트 관련 도서를 빌렸다.

너무 오랜만에 봐서 그런지 다시 입문하는 느낌이다.

워낙 공부를 띄엄띄엄해서 다시한번 쭈욱 훑는 느낌으로 읽고 실습해보려한다.




다음함수를 만드시오

매개변수를 하나 넣으면 제곱해준다.
매개변수를 2개넣으면 <첫번째 매개 변수>의 <두번째 매개변수> 제곱만큼 해준다.


let power ;

      power = function(a,b){
        if(b=b||2)
        console.log(Math.pow(a,b));
      }

      power(9);

매개변수로 넣은 값을 모두 곱해준다.

let mutiply ;

      multiply = function(){
        let mul =1;

        for(let i=0, j= arguments.length; i<j; i++){
          mul *= parseInt(arguments[i]);
        }

        console.log(mul);
      }

      multiply(1,2,3,4,5);


2016년 10월 1일 토요일

learning underscore.js 원서 읽으며 연습하기!

page 33 개인적으로 잘몰라서 주석을 넣어보았다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var propertyExtractor  = (function(){
  "use strict";
  return {
    extractStorableProperties: function(source){
      var storableProperties = {};
      // +사인은  숫자형으로 변환한다.
      // !==는 오리지널 값과 숫자형으로 변환된 값을 비교하는  비 식별 연산자이기 때문에...
      // === non-identity operator는 true를 반환하는 경우는 2가지다
      // 1. 비교된 객체의 유형이 다른경우                      - 예)  1 !== '1' 의 비교  값을 var a  = function(){ return '1' }();
      // 2. 비교된 객체가 같은 타입이지만 다른 값을 갖는 경우      - 예)  2 !== 3
      if(!source||source.id !== +source.id){    // source가 있어야하며 source.id를 비교 (+source.id는 의미를 모르겠다.)
        return storableProperties;
      }
 
      //조건에 합당한경우 추출 대상 콜렉션 : source
      _.each(source, function(value,key){
        // 값이 객체여야하며, Date의 인스턴스일경우 isDate는 true
        var isDate = typeof value === 'object' &&  value instanceof Date;
 
        // isDate가 true 인경우(날짜) || value가 숫자형일경우 || 문자형일경우  결국 value 값이 저장가능한
        // 날짜형, 숫자형, 문자형 인경우 key와 value를 객체에 저장하겠다.
        if(isDate|| typeof value === 'boolean'|| typeof value === 'number' || typeof value ==='string'){
          storableProperties[key] = value;
        }
 
      });
      return storableProperties;
    }
  }
}());
cs

2016년 9월 28일 수요일

러닝 언더스코어 .js 책의 목차

1장. Underscore.js 시작하기
__왜 Underscore인가
__예제로 Underscore 시작하기
____ECMAScript 5 초보 예제
____Underscore의 find를 적용한 초보 예제
____Underscore의 countBy를 적용한 초보 예제
__Underscore 핵심 함수
____Underscore의 each
____Underscore의 map과 reduce
__함수형 프로그래밍 기본
__ECMAScript 5를 대상으로 한 자바스크립트 애플리케이션에서의 유용한 패턴과 실례
____즉시 실행 함수 표현
____노출식 모듈 패턴
____자바스크립트 엄격 모드
__Underscore를 살펴보기 위한 개발 워크플로우 설정
____Node.js로 자바스크립트 개발하기
________윈도우
________맥 OS X
________리눅스
________Node.js 설치 확인
____Bower로 자바스크립트 의존성 관리하기
____자바스크립트 편집기 고르기
__Jasmine으로 자바스크립트 코드 테스트하기
____Jasmine 소개
____기본 Jasmine 인프라를 사용한 테스트 추가하기
__요약

2장. Underscore.js에서 컬렉션 사용하기
__Underscore 핵심 함수 다시 보기: each, map, reduce
____리플렉션 기술 적용하기
____this 변수 조작하기
____객체 프로퍼티에 map과 reduce 사용하기
__탐색과 필터링
____탐색하기
________Underscore의 find
________Underscore의 some
________Underscore의 findWhere
________Underscore의 contains
____필터링
________Underscore의 filter
________Underscore의 where
________Underscore의 reject와 partition
________Underscore의 every
__집계와 변환
____집계
________Underscore의 max와 min
____변환
________Underscore의 sortBy
________Underscore의 groupBy
________Underscore의 indexBy
________Underscore의 countBy
__기타 컬렉션 기반 함수들
__요약

3장. Underscore에서 배열, 객체, 함수 사용하기
__배열
____배열의 처음과 끝 추출하기
____합집합, 교집합, 관계 함수
____배열 관련 기타 함수
__객체
____Underscore의 keys
____Underscore의 values와 pairs
____Underscore의 invert와 functions
____Underscore의 pick, omit
____Underscore의 extend, clone, defaults
____Underscore의 has, property, propertyOf, matcher
____객체 간 비교와 객체에 대한 표명
____다른 객체 관련 기타 함수
__함수
____bind, bindAll, partial로 함수 합성하기
____memoize, wrap, negate, compose로 함수 합성하기
____함수의 호출 시간 및 횟수 제어하기
__유틸리티 함수
__요약

4장. Underscore.js에서의 프로그래밍 패러다임
__객체지향 프로그래밍 패러다임
____객체 리터럴로 상속하기
____객체 생성자로 상속하기
____Underscore를 사용한 객체지향 프로그래밍 패러다임
________원본 고객 데이터로 클래스 사용하기
________Underscore로 생성자 검증하기
__함수형 프로그래밍 패러다임
__함수형 프로그래밍 스타일로 전환하기
__Underscore를 사용한 함수형 프로그래밍
__요약

5장. 서버의 브라우저에서 데이터베이스를 이용한 Underscore.js 사용하기
__브라우저에서 Underscore 사용하기
__부트스트랩을 사용해 향상된 예제 결과 얻기
____Underscore 템플릿을 사용해 더 나은 HTML 마크업 사용하기
__Node.js를 가지고 서버에서 Underscore 사용하기
____Node.js를 가지고 자바스크립트 실행하기
____Node.js 모듈 사용하기
____모듈 위치 관련
____npm 패키지 만들기
____자바스크립트 코드를 Node.js 모듈로 변경하기
____Node.js로 테스트하기
__MongoDB와 함께 Underscore 사용하기
____MongoDB 설치하고 설정하기
________윈도우에서 MongoDB 설치하기
________우분투 리눅스에서 MongoDB 설치하기
________맥 OS X에서 MongoDB 설치하기
________MongoDB 설정하고 동작시키기
____MongoDB 클라이언트와 Underscore를 사용해 초기 데이터 만들기
____Node.js를 사용한 비동기 프로그래밍
____MongoDB Node.js 드라이버를 사용해 데이터 접근하기
__PostgreSQL을 가지고 Underscore 사용하기
____PostgreSQL 설치하고 설정하기
________윈도우에서 PostgreSQL 설치하기
________우분투 리눅스에서 PostgreSQL 설치하기
________맥 OS X에서 PostgreSQL 설치하기
____기본 데이터베이스 명령을 가지고 psql 사용하기
____PostgreSQL 데이터 타입
________SQL 타입
________jsonb 타입
____plv8을 가지고 PostgreSQL 사용하기
____plv8과 Underscore를 사용해 데이터 만들기
__요약

6장. 관련된 Underscore.js 라이브러리와 ECMAScript 표준
__Underscore-contrib 라이브러리 사용하기
____Underscore-contrib 기능 소개
____Underscore-contrib의 예
__lodash 라이브러리 사용
____lodash 기능 소개
____Underscore에서 lodash로의 프로젝트 마이그레이션
__Underscore와 자바스크립트 표준
____ECMAScript 5.1(ES5)
____ECMAScript 2015(ES6)
________배열: 새로운 기능
________그 외 중요한 새로운 기능
________현재 ECMAScript 2015(ES6)와 트랜스파일러
________ECMAScript 2015(ES6) 예제
__요약

7장. Underscore.js 빌드 자동화와 코드 재사용성 살펴보기
__Gulp를 이용한 빌드 자동화
__클라이언트와 서버 간의 Underscore 기반 코드 재사용
____Browserify를 이용한 클라이언트 코드 패키징을 위한 CommonJS 모듈
____Browserify를 이용한 브라우저에서의 CommonJS 모듈 테스팅
____Browerify와 Gulp의 통합
__Browserify의 ECMAScript 2015(ES6) 지원
__요약




Book Details

Publisher:Packt Publishing
By:Alex Pop
ISBN:978-1-78439-381-6
Year:
Pages:224
Language:English
File size:11 MB
File format:PDF


2016년 9월 26일 월요일

functional javascript를 읽으며...

1장 함수형 프로그래밍이란 이런것이다.

함수형태로 '존재'의 추상화를 정의한다.
기존 함수를 이용해서 '참 거짓' 의 추상화를 정의한다.
위 함수를 다른 함수의 파라미터로 제공해서 어떤 동작을 하도록 한다.

코딩트레이닝 2-3

<script>

    //입력

    var inputString = prompt('인용구 연습 ', '예) 죽느냐사느냐 그것이 문제로다, 햄릿');

    var inputArr = inputString.split(',');

    //These aren't the droids you're looking for, Obi-Wan Kenobi


    //처리
    var tweets = inputArr[0];
    var tweeter = "『"+inputArr[1]+"』";

    var firstline = "What is the quote?  " + tweets;
    var secondline = "Who said it?  " + tweeter;
    var thirdline = tweeter + " says, \" "+tweets + " \" "


    //출력
    $(document).ready(function(){


      $('#foo').append(firstline+"<br>").append(secondline+"<br>").append(thirdline);

    });

    </script>


죽느냐 사느냐 그것이 문제로다 -세익스피어 인줄알았음

아주 큰창피를 당할뻔했어

코딩트레이닝 2-2

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
    <script type="text/javascript">

    var name, leng_name,str;

    //입력

    name = prompt('이름을 입력해주세요');

    //처리
    leng_name = name.length;

    str = '<div > <h2>What is the input string? <p id="display_name">'+ name
    +'<br> '+ name + ' has</p></h2> <p id="display_name_count">' +leng_name  + ' </p>charaters </div>';


    //출력

    $(document).ready(function(){


      //처리

      //텍스트 박스의 내용이 입력되었을때
      $('#name').change(function(){

        //디브 - h2 - p의 내용이 변경되어야 한다. 이름 / 이름의 수
        name = $('#name').val();
        leng_name = name.length;

        $('#display_name').text(name);
        $('#display_name_count').text(leng_name);

      })


      //출력

      $('#foo').append(str);
    });


    </script>
  </head>
  <body>

    <div id="foo">
      <input type="text" id="name">
    </div>

  </body>
</html>



2016년 9월 25일 일요일

코딩트레이닝 2-1

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
    <script>

    //입력
    // var name = prompt('input your name');
   
    //처리
    // var str = "<h2>What is your name? Hello "+name+ ", nice to meet you!<h2>";

    //랜덤 배열
    var textArray = [
      '호 키 포키! ',
      '아빠 상어 뚜루뚜뚜루',
      '뚜뚜뚜와 뚜뚜뚜뚜와뚜와!'
    ]
    var randomNumber = Math.floor(Math.random() *textArray.length);

    //출력
    $(document).ready(function(){

      $('#foo').append('<h2>What is your name? <br> Hello '+ prompt('input your name')+ ', nice to meet you!<h2> <br>'+textArray[randomNumber]);
    });

    </script>
  </head>
  <body>
    <div id="foo">

    </div>

  </body>
</html>


이름을 입력받는것은 변수없이 구현

코딩트레이닝 첫번째 실습 코드



<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js">
    </script>
    <script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
    <script type="text/javascript">

    function lalala(){
      return "lalala";
    }

    /*
      팁 계산기

      이 프로그램이 받는것은 가격 price 팁비율 tip_ratio

      주 기능은

      팁을 계산하여 팁과 전체 가격을 표시해 주는것이다.


    */

    //출력

    window.onload = function(){

      var inputvalues
      var inputArr

      var price
      var ratio

      function promptVal(){

        inputvalues = prompt('가격과 할인률을 ,로 구분하여 입력하여 주세요','ex) 15,11');
        inputArr = inputvalues.split(',');

        //음수값일경우 절대값으로 변환
        if(inputArr[0]< 0) {
          console.log(inputArr[0]);
          inputArr[0] = Math.abs(inputArr[0]);
        }

        price = parseInt(inputArr[0]);
        price.toFixed(2);

        console.log(isNaN(price), typeof(ratio));

        ratio = parseInt(inputArr[1]);
      }

      while(isNaN(price)){
        promptVal();
      }

      var tip,total;

      function calcTip(price, ratio){
        tip = price * (ratio/100);
        tip = parseFloat(tip.toFixed(2));
        total = parseFloat(parseFloat(price) + tip);
      }

      calcTip(price, ratio);
      refreshView();


      $('#price').focusout(function(){
        price = $('#price').val();
        calcTip(price, ratio);
        refreshView();

      });

      $('#ratio').change(function(){
        ratio = $('#ratio').val();
        calcTip(price, ratio);
        refreshView();

      });

      $('#tip').focusout(function(){
        tip = $('#tip').val();
        calcTip(price, ratio);
        refreshView();

      });

      $('#total').focusout(function(){
        total = $('#total').val();
        calcTip(price, ratio);
        refreshView();

      });

      function refreshView(){
        //가격
        $('#table1 tr:nth-child(1) td:nth-child(2) input').val(price);
        //비율
        $('#table1 tr:nth-child(2) td:nth-child(2) input').val(ratio);
        //팁
        $('#table1 tr:nth-child(3) td:nth-child(2) input').val(tip);
        //토탈
        $('#table1 tr:nth-child(4) td:nth-child(2) input').val(total);
      }
    }
    </script>
    <title></title>
  </head>
  <body>

    <table border=1 id="table1">

      <tr>
        <td>가격</td>
        <td ><input type="text" id="price"></td>
      </tr>
      <tr>
        <td>팁 비율</td>
        <td ><input type="range"  min="0" max="20" id="ratio" /></td>
      </tr>
      <tr>
        <td>팁 </td>
        <td ><input type="text" id="tip"></td>
      </tr>
      <tr>
        <td>합산가격</td>
        <td ><input type="text" id="total"></td>
      </tr>

    </table>
  </body>
</html>

-- index.html


자바스크립트로 연습해 보았습니다 ^^

2016년 9월 1일 목요일

자바스크립트를 깨우치다. 첫날

원시값은 "값으로 참조" 되지 않고 다른 여러 값으로 구성된합성체를 표현할 수 없는 반면,
복합객체는 "값으로 참조"되며 다른 값을 포함하거나 캡슐화할 수 있다.

 new키워드를 사용해서 객체를 만들면 복합객체
new를 사용하지 않고 예를들어
let primitiveNumber2 = Number('22') 이런식으로 변수를 선언하면 원시값을 갖게된다.

2015년 10월 20일 화요일

javascript 함수는 찾는데 실행이 안될때

말그대로 자바스크립트 함수는 찾는데 실행이 안되는때가 있었다. 언제? 오늘 1시간정도 전에

$("#ID").on("change", function(){


});

상단에 머 이런 이벤트 핸들러는 잘 동작하는데

 function check_***(){


};

function delete_***(){

}

이런 함수가 있었고

html에서는 a 태그의 href="javascript:delete_***();" 이런식으로 호출을 했었는데
함수는 찾는다 그러니까 undefined이런 에러는 뿜지 않는데 실행이 안되는거다.

묵묵 부답 분명히 상단의 이벤트는 잘동작하는데
다른 함수를 만들어봐도 실행은 안되고 검색만 2시간 가량 하다가 브라우저의 캐시를 날려보니

잘되더라....

장난하니? 자바스크립트는 디버깅도 쉽지않은데 (f12키 를 누르면 나오는 개발자모드는 있지만)
이런경우는 찾기 쉽지가 않다.

정작 해야할일은 산더미인데 이렇게 자바스크립트가 안되는 문제로 발목을 잡히면  ㅠㅠ



2015년 2월 4일 수요일

자바와 자바스크립트의 차이?

음 언어의 차이입니다. 라고 대답하면 상대방은 '이게 지금 나를 무시하는건가?' 라고 생각할지도 모르겠으나 <

사실 전혀 다른 언어가 아닐까 합니다.

자바는 객체지향 언어입니다. 자바라는 언어로는 객체지향적으로 설계하여 코드를 작성한다고 말하는게 맞을거 같고 (클래스를 만들고 상속및 구현을 사용하여 인스턴스화 해서 사용한다.)

자바스크립트는 객체지향으로 설계를 해도 되긴합니다. 그런데 그건 자바스크립트를 제대로 사용하는 방법이 아니라고 알고있습니다.

문법은 살짝 비슷하다고 할수 있지만 약간의 차이가 있습니다.

자바스크립트는 프로토타입 기반 프로그래밍 언어로 보는게 좀더 정확할듯합니다.

프로토타입 기반 프로그래밍은 객체지향 프로그래밍의 한 형태의 갈래로 클래스가 없고, 클래스 기반 언어에서 상속을 사용하는 것과는 다르게, 객체를 원형(프로토타입)으로 하여 복제의 과정을 통하여 객체의 동작 방식을 다시 사용할 수 있다. 프로토타입기반 프로그래밍은 클래스리스(class-less), 프로토타입 지향(prototype-oriented) 혹은 인스턴스 기반(instance-based) 프로그래밍이라고도 한다.


사실 저도 공부중이라 명확하게 정의는 할수 없으나

자바스크립트의 특징을 말하라면 아무래도 '프로토타입 기반 프로그램언어다' 라고 말할 수는  있어야 겠다 생각되네요.

자바스크립트 기초 3가지

스코프체인

클로저

자바스크립트엔진





javascript inside  , 단일페이지 웹어플리케이션

책 두권 모두 위의 3가지가 잘  설명되어 있습니다.

2015년 1월 30일 금요일

과거 브라우저에서의 Object.create 사용

Object.create는 인터넷익스플로러9이상, 파이어폭스 4이상 사파리5이상 크롬 5이상의 버전부터 지원한다. 구닥다리 브라우저에서는 Object.create메서드를 구현해야한다.
//Object.create(를 지원하지 않는 브라우저를 위한 크로스 브라우저 메서드

var objectCreate = function(arg){
if(!arg) {return{};}
function obj(){};
obj.prototype = arg;
return new obj;
};
Object.create = Object.create || objectCreate;

2014년 11월 7일 금요일

안된다 안된다 안된다 ㅠㅠ 왜?


module.js:340
    throw err;
          ^
Error: Cannot find module 'connect'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Users\sharpscar\workspace\helloWorld\hello-world-server.js:4:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)


connection 모듈을 못찾는다
서적에 package.json파일에 대해나오는데 소스또한 부분적으로 안보여서 해당 프로젝트 위치에서 커맨드라인 켜고
npm init 이란명령어로 몇개 넣어주고
"dependencies" : {
"connect" :"*"
}해주고 나서 json파일을 npm install하면
프로젝트 폴더 밑에 node_modules폴더가 생기면서
커넥트 미들웨어가 설치가 되어야 정상

그러면서 관련 예제가 실행되어야되는데 위와같은 에러를 뿜는다 난 분명히 설치해줬는데 얘는 에러를 뿜는 현상

구글에 검색해봐도 무슨말인지 도통 모르겠다
예전에도 express에서 미들웨어들이 대거 분리되었다는 말을 듣긴 했는데 그거하고 이문제가 관련이 있는지 모르겠다

우선 시간이 지체되는것같아 넘어가고 다음장

Persisting Data부터 읽어보기로 결정

7장은 시간있을때 다시보거나 다른 서적을통해 공부하도록 해야겠다.

node.js 의 url모듈

url을 객체화 할때는 url.parse()메서드를 사용
다시 직렬화 할때는 url.format()메서드를 사용

var url = require('url');

var obj = url.parse('https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=sharpscar\'s%20crab%20pot');
console.log('url to Object : ', obj);
console.log("=====================");
console.log('Object to URL :', url.format(obj));


결과

url to Object :  { protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.google.co.kr',
  port: null,
  hostname: 'www.google.co.kr',
  hash: '#newwindow=1&q=sharpscar%27s%20crab%20pot',
  search: '?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8',
  query: 'sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8',
  pathname: '/webhp',
  path: '/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8',
  href: 'https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=sharpscar%27s%20crab%20pot' }
=====================
Object to URL : https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=sharpscar%27s%20crab%20pot

nodejs 동기식 비동기식 파일읽기와 파일 확인

비동기식
var fs = require('fs');
fs.readFile('test.txt','utf8',function(err,data){
if(err) throw err;
console.log(data);
});

동기식
var fs = require('fs');
var data = fs.readFileSync('test.txt', 'utf8');
console.log(data);


비동기 파일확인
fs.exists('test1.txt', function(exists){
  console.log('fs.exists: ' ,exists);
}

동기식 파일확인
var exists = fs.existsSync('test.txt');
console.log('fs.existsSync : ' , exists);

2014년 11월 5일 수요일

nodeunit사용 피보나치 수열 테스트

t\lib\types.js:83:39)
    at Object.exports.testGetFibonaccieNumber (C:\Users\sharpscar\workspace\hell
oWorld\test\fibonaccie-nodeunit-tests.js:10:7)
    at Object.<anonymous> (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\n
odeunit\lib\core.js:236:16)
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\lib\core.js:
236:16
    at Object.exports.runTest (C:\Users\sharpscar\AppData\Roaming\npm\node_modul
es\nodeunit\lib\core.js:70:9)
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\lib\core.js:
118:25
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\deps\async.j
s:513:13
    at iterate (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\dep
s\async.js:123:13)
    at async.forEachSeries (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\
nodeunit\deps\async.js:139:9)
    at _concat (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\dep
s\async.js:512:9)

Assertion Message: Wrong fibonaccie!! 10th fibonaccie number is 34!!
AssertionError: 256 == 34
    at Object.equal (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeuni
t\lib\types.js:83:39)
    at Object.exports.testGetFibonaccieNumber (C:\Users\sharpscar\workspace\hell
oWorld\test\fibonaccie-nodeunit-tests.js:11:7)
    at Object.<anonymous> (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\n
odeunit\lib\core.js:236:16)
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\lib\core.js:
236:16
    at Object.exports.runTest (C:\Users\sharpscar\AppData\Roaming\npm\node_modul
es\nodeunit\lib\core.js:70:9)
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\lib\core.js:
118:25
    at C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\deps\async.j
s:513:13
    at iterate (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\dep
s\async.js:123:13)
    at async.forEachSeries (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\
nodeunit\deps\async.js:139:9)
    at _concat (C:\Users\sharpscar\AppData\Roaming\npm\node_modules\nodeunit\dep
s\async.js:512:9)


FAILURES: 3/3 assertions failed (15ms)






C:\Users\sharpscar\workspace\helloWorld\test>nodeunit fibonaccie-nodeunit-tests.
js

fibonaccie-nodeunit-tests.js
Let's get Fibonaccie Numbers...
Fibonacci [8] th Number is [13]
All numbers is [0,1,1,2,3,5,8,13]
Let's get Fibonaccie Numbers...
Fibonacci [9] th Number is [21]
All numbers is [0,1,1,2,3,5,8,13,21]
Let's get Fibonaccie Numbers...
Fibonacci [10] th Number is [34]
All numbers is [0,1,1,2,3,5,8,13,21,34]
✔ testGetFibonaccieNumber

OK: 3 assertions (16ms)

C:\Users\sharpscar\workspace\helloWorld\test>


위가 테스트 했을때  원치않는 값이 나왔을경우
아래가 테스트 했을때 원하는 값이 나올경우

Node js 프로그래밍 책을 보고있습니다.

이클립스를 설치한후에

추가프로그램으로 nodeclips를 추가한후

간단한 피보나치 수열을 계산하는 소스를 작성해봅니다.

그리고나서

해당 js파일에서 우클릭 -> Debug as -> Node Application메뉴를 선택하면 4개의 창으로 구분되어집니다.

중단 창에서 F5~ F8키의 기능을 정리해봅니다.

F5키 : Step info : 해당 스텝 안으로 들어갑니다. 스텝에 함수가 있다면 해당 함수 안으로 들어갑니다.
F6키 : Step over 해당 스탭 다음으로 넘어갑니다.  지금 디버깅 하고 있는 소스 라인의 다음 라인으로 이동한다는 것을 의미
F7키 : Step Return 해당 스텝 밖으로 나갑니다. 특정 함수 안 이였다면 함수를 호출했던 소스로 나갑니다.
F8키 : Resume 다음 브레이크 포인트까지 소스를 진행합니다.



Nodeunit을 활용한 단위 테스트

https://github.com/caolan/nodeunit  <<

*ok(value,[message])
 -test if value is a true value
*equal(actual, expected, [message])
 -tests shallow, coercive equality with the eqaual comparison operator(==).
*notEqual(actual, expected, [message])
-tests shallow,coercive non-equality with the not equal comparison operator(!=).
*deepEqual(actual, expected,[message])
-test for deep equality
*strictEqaul(actual,expected, [message])
-tests strict equality, as determined by the strict equality operator(===)
*throws(block,[error], message])
-Expectsblock to throw an error
*doesNotThrow(block,[error],[message])
-expects block not to throw an error
*ifError(value) -test if value is not a false value, throws if it is a true value. useful when lesting the fist argument, error in callbakcs.


  • expect(amount) 해당 테스트 케이스에 몇개의 assert함수가 있는지를 명시합니다. 테스트시 개발자가 의도했던 Assert함수가 모두 수행됐는지 쉽게 확인할수 있습니다.
  • done() - 테스트 케이스의 종료를 명시하고 다음 테스트 케이스를 수행하게 합니다. 해당메소드는 반드시 호출해야 합니다.




2014년 10월 12일 일요일

진작에 읽어보고싶고 읽어봐야할 책들

익스프레스 프레임워크로 하는 노드 웹 앱 프로그래밍
익스프레스 프레임워크로 하는 노드 웹 앱 프로그래밍

AngularJS로 하는 웹 애플리케이션 개발

AngularJS로 하는 웹 애플리케이션 개발






(실무환경에 맞춘) Node.js 프로그래밍 : 자바스크립트, 서버까지 점령하라  << 도서관 대여 예정

Node.js 인 액션 : 베테랑 개발자가 전하는 노드제이에스 완벽 활용법  << 한번 읽어봤는데 이해가 어려움 재대여예



책은 도끼다 << 001.3-박웅현책

배움을 돈으로 바꾸는 기술 : 부를 끌어당기는 부자들의 공부법 / 이노우에 히로유키 지음 ; 박연정 옮김
325.04 

 돈으로 살 수 없는 것들 : 무엇이 가치를 결정하는가 / 마이클 샌델 지음 ; 안기순 옮김 193