Created
October 24, 2019 06:58
-
-
Save cojj90/d107c7fa8b9e029167cc217831e48a60 to your computer and use it in GitHub Desktop.
tag checker exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { assertNever } from 'assert-never' | |
const VALID_OUTPUT = 'Correctly tagged paragraph' | |
enum TAG_TYPE { | |
OPENING, | |
CLOSING | |
} | |
const tagParser = (tag: string) => { | |
if (tag.startsWith('</')) { | |
const value = tag.charAt(2) | |
return { type: TAG_TYPE.CLOSING, value } | |
} | |
if (tag.startsWith('<')) { | |
const value = tag.charAt(1) | |
return { type: TAG_TYPE.OPENING, value } | |
} | |
throw Error('Invalid Tag Input') | |
} | |
const basicTagChecker = (input: string) => { | |
const tags = input.match(/<([A-Z]|\/[A-Z])>/g) | |
if (tags == null) return VALID_OUTPUT | |
const stack: string[] = [] | |
let error | |
tags.some((tag) => { | |
const parsedTag = tagParser(tag) | |
const { type, value } = parsedTag | |
switch (type) { | |
case TAG_TYPE.OPENING: | |
stack.push(value) | |
break | |
case TAG_TYPE.CLOSING: | |
const lastOpenedTag = stack.pop() | |
if (lastOpenedTag == null) { | |
error = `Expected # found </${value}>` | |
return true | |
} | |
if (value !== lastOpenedTag) { | |
error = `Expected </${lastOpenedTag}> found </${value}>` | |
return true | |
} | |
break | |
default: | |
assertNever(type) | |
break | |
} | |
}) | |
if (error != null) return error | |
if (stack.length === 0) return VALID_OUTPUT | |
const lastTag = stack.pop() | |
return `Expected </${lastTag}> found #` | |
} | |
export { basicTagChecker } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment