Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
2a99f6b
isNaN(Number(token))) === true 의 === 와 true제거
HTMLhead Nov 16, 2018
99b0112
for문을 for of문으로 변경, count => quotesCount
HTMLhead Nov 16, 2018
cf467b2
jsondata를 만들때 object타입일때를 대비하여 keyValue값 추가
HTMLhead Nov 16, 2018
9f3de4b
설계파일 생성
HTMLhead Nov 16, 2018
a7b604d
설계 완성
HTMLhead Nov 16, 2018
1727718
JSONdata class의 keyvalue값 제거
HTMLhead Nov 16, 2018
9c0955d
getToken함수에 {값과 :값, }값을 통해 원하는 대로 token화 시킬수 있도록 만듬
HTMLhead Nov 16, 2018
9476029
getChild 에서 {값이 주어진다면 만드는 값 생성
HTMLhead Nov 16, 2018
1866700
:값이 포함되어 있는 값이 주어진다면 key값으로 만드는 조건문 완성
HTMLhead Nov 16, 2018
c5c67e6
}값이 나오면 반복문 탈출하도록 조건문 완성
HTMLhead Nov 16, 2018
c5fd338
요구사항을 체크하며 수행하기 위해 주석처리한 요구사항을 만듬
HTMLhead Nov 16, 2018
e67431d
마지막 함수를 변수는 짧게 함수 이름은 길게 만듬
HTMLhead Nov 16, 2018
ac1ace3
queue함수수정시작
HTMLhead Nov 16, 2018
b7435bb
queue메서드 내에 필요한 메서드 makeArrayChild, makeObjectChild껍데기 제작
HTMLhead Nov 16, 2018
4086651
makeArrayChild함수 완성
HTMLhead Nov 16, 2018
ae9212e
queue 함수에 적용
HTMLhead Nov 16, 2018
0a659ec
makeObjectChild함수 완성
HTMLhead Nov 16, 2018
8249b68
queue에 적용
HTMLhead Nov 16, 2018
7ef1e04
getChild함수 수정시작, checkingValue가 }나 ]일때 같은 동작을 하도록 수정
HTMLhead Nov 16, 2018
1a63c02
analyze 객체 수정 일단락
HTMLhead Nov 16, 2018
ea997ec
conutQueueNum함수 제작
HTMLhead Nov 16, 2018
9f5c786
countQueueNum함수 완성, checkString에 적용
HTMLhead Nov 16, 2018
3a8bb6c
this 추가
HTMLhead Nov 16, 2018
8f8b375
errorCheck 객체 수정 일단락
HTMLhead Nov 16, 2018
7915454
analyze객체 수정 시작
HTMLhead Nov 16, 2018
0feb928
analyze말고 errorcheck객체에서 해결해야하는 문제임을 깨닫고, errorCheck객체 수정 시작
HTMLhead Nov 16, 2018
66270a7
printErrorMessage 함수 생성
HTMLhead Nov 16, 2018
7dc109a
printErrorMessage 함수 생성
HTMLhead Nov 16, 2018
75fe5cd
checkString 메서드와 checkNumber메서드에 printErrorMessage메서드 적용
HTMLhead Nov 16, 2018
e563e5c
token 추가
HTMLhead Nov 16, 2018
528771a
analyze객내의 getChild함수에 checkError객체 내의 변경된 함수 적용
HTMLhead Nov 16, 2018
e922b9e
주석과 디버거 제거
HTMLhead Nov 16, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 65 additions & 35 deletions jsonParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ class JSONData {
this.child = child
}
}

const sentence = "['1a'3',[22,23,[11,[112233],112],55],33]".replace(/ /gi, '')
const sentence = "['1a3',[null,false,['11',[112233],{easy : ['hello', {a:''a'}, 'world']},112],55, '99'],{a:'str', b:[912,[5656,33],{key : 'innervalue', newkeys: [1,2,3,4,5]}]}, true]".replace(/ /gi, '')

class Tokenize {
constructor() {
this.wholeDataQueue = [];
}

getWholeDataQueue(sentence) {
while(sentence.length !== 0) {
while (sentence.length !== 0) {
const token = this.getToken(sentence)
this.wholeDataQueue.push(token)
sentence = sentence.replace(token, '')
Expand All @@ -23,12 +22,16 @@ class Tokenize {
}

getToken(str) {
if (str[0] === '[' || str[0] === ',' || str[0] === ']') {
if (str[0] === '[' || str[0] === ',' || str[0] === ']' || str[0] === '{' || str[0] === '}') {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조건문이 너무 길어요. 이런것도 함수로 구현할 수 있으면 좋겠네요.

ch = "]";
const delimiters = ["[", "]", "{", "}", ","];
result = delimiters.some(v => v === ch);

return str.slice(0, 1)
} else if (str.indexOf(']') < str.indexOf(',')) {
return str.slice(0, str.indexOf(']'))
} else if (str.indexOf(',') === -1) {
return str.slice(0, str.indexOf(']'))
} else if (str.indexOf(':') !== -1 && str.indexOf(',') > str.indexOf(':')) {
return str.slice(0, str.indexOf(':') + 1)
} else if (str.indexOf('}') < str.indexOf(',')) {
return str.slice(0, str.indexOf('}'))
} else {
return str.slice(0, str.indexOf(','))
}
Expand All @@ -40,76 +43,103 @@ class Analyze {
this.queueArr = queue
this.errorCheck = errorCheck
}

queue() {
while(this.queueArr.length !== 0) {
while (this.queueArr.length !== 0) {
const value = this.queueArr.shift()
if(value === '[') {
const child = this.getChild(this.queueArr, value)
return new JSONData('Array', 'Array Object', child)
if (value === '[') {
return this.makeArrayChild(this.queueArr, value)
} else if (value === '{') {
return this.makeObjectChild(this.queueArr, value)
}
}
}

makeArrayChild(queueArr, value) {
const arrayChild = this.getChild(queueArr, value)
return new JSONData('Array', 'Array Object', arrayChild)
}

makeObjectChild(queueArr) {
const objectChild = this.getChild(queueArr, value)
return new JSONData('Object', 'Object Object', objectChild)
}

getChild(queueArr, checkingValue) {
let child = [];
debugger;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다음엔 debugger 코드 삭제해주세요~ 실제 서비스할때는 이런 디버깅코드는 당연히 없어야겠죠. console.log도 마찬가지로 제거해야하고요.

Copy link
Copy Markdown
Author

@HTMLhead HTMLhead Nov 19, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네....죄송합니다. 실수했네요 앞으로 꼭 debugger와 console.log를 검색으로 찾아서 다 지운 다음 보내겠습니다. 구현이 되었다는거에 설레서..하하하하

while (checkingValue !== ']') {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getChild 의 조건문이 많은 건 어쩔 수 없어보여요.
파싱이라는 특별한 로직에서 생길 수 있는 정상적인 statement 라고 생각해요. 괜찮아요.

조건상황을 함수로 모두 다 구현할 수도 있긴합니다. 예를들어,
checkingValue === 'true' || checkingValue === 'false'
이코드를 if(isBoolean(checkingValue)) 이런식으로..수정할 수 있겠죠.

그리고 참고로 조건문이 많아지면, 불필요한 체크를 조금이라도 줄이기 위해서,
좀더 자주 발생하는 조건문을 앞쪽에 배치하려고 하는 것을 신경쓸 필요가 있죠.

checkingValue = queueArr.shift()
if(checkingValue === '[') {
if (checkingValue === '[') {
child.push(new JSONData('Array', 'Object Array', this.getChild(queueArr, checkingValue)))
continue;
} else if (checkingValue === ',') {
} else if (checkingValue === '{') {
child.push(new JSONData('Object', 'Object Object', this.getChild(queueArr, checkingValue)))
continue;
} else if (checkingValue === ']') {
} else if (checkingValue.indexOf(':') !== -1) {
child.push(new JSONData('object key', checkingValue.slice(0, checkingValue.indexOf(':')), []))
continue;
} else if (checkingValue === '}' || checkingValue === ']') {
break;
} else if (checkingValue === ',') {
continue;
} else if (checkingValue === 'true' || checkingValue === 'false') {
child.push(new JSONData('Boolean', checkingValue, []))
continue;
} else if (checkingValue === 'null') {
child.push(new JSONData('Null', checkingValue, []))
continue;
} else if (checkingValue[0] === "'") {
if(this.errorCheck.checkString(checkingValue)) {
console.log(`${checkingValue}는 제대로된 문자열이 아닙니다.`)
return
}
if (this.errorCheck.checkString(checkingValue)) return
child.push(new JSONData('String', checkingValue, []))
continue;
}
if(this.errorCheck.checkNumber(checkingValue)) {
console.log(`${checkingValue}은 알수없는 문자열입니다.`)
return
}
if (this.errorCheck.checkNumber(checkingValue)) return
child.push(new JSONData('Number', checkingValue, []))
}
return child
}
}
};

class ErrorCheck {
checkString(token) {
debugger;
let count = 0
for(let position = 0; position < token.length; position++) {
if(token[position] === "'") {
count++
class ErrorCheck {
countQueueNum(token) {
let quotesNum = 0
for(let position of token) {
if(position === "'") {
quotesNum++
}
}
if(count === 2 && token[0] === "'" && token[token.length-1] === "'") {
return quotesNum
}

checkString(token) {
let quotesNum = this.countQueueNum(token)
if (quotesNum === 2 && token[0] === "'" && token[token.length - 1] === "'") {
return false
}
this.printErrorMessage('string', token)
return true
}

checkNumber(token) {
if(isNaN(Number(token)) === true) {
if (isNaN(Number(token))) {
this.printErrorMessage('number', token)
return true
}
return false
}
}

function printJSONData(JSONData) {
printErrorMessage(type, token) {
if(type === 'string') {
console.log(`${token}는 제대로된 문자열이 아닙니다.`)
}
if(type === 'number') {
console.log(`${token}은 알수없는 데이터입니다.`)
}
}
};

const print = function printJSONData(JSONData) {
console.log(JSON.stringify(JSONData, null, 2))
}

Expand All @@ -118,5 +148,5 @@ const tokenizedDataArr = tokenize.getWholeDataQueue(sentence)
const errorCheck = new ErrorCheck
const analyze = new Analyze(tokenizedDataArr, errorCheck)
const jsonData = analyze.queue()
printJSONData(jsonData)
print(jsonData)

4 changes: 4 additions & 0 deletions step5LayOut.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
* 토큰나누기를 할때, '{' 값과 '}' 값을 따로 나눔,:는 key값과 같이 있을 수 있도록 나눔"{'dominate':13}"를 나눈걸 예시로들면
['{','dominate:','13','}']이런 형식으로 나눌 수 있도록. ':'값이 존재하면 ':'값 이전까지 type이 object key인 value 값에 넣어 주도록 하고, child는 '[]' 로.

* 분석을 할때, { 값이 나오면 새로운 제이슨 데이터를 만들도록. child에는 getChild가 여전히 들어가도록 하고, { 다음에 오는 값은 무조건 ':' 를 포함하고 있을 테니, 그값만 key로 만들고 뒤의 값은 이전과 같은 방식으로 만들 수 있도록 하기. '}'가 나올때 까지.