Last active
September 19, 2016 07:30
-
-
Save stsatlantis/1f0897555492f70ba5d8cd367d94e35b to your computer and use it in GitHub Desktop.
CodeFight - htmlToLuna
This file contains hidden or 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
| def htmlToLuna(html: String): String = { | |
| abstract class HtmlElement{def print(): String} | |
| case class Div(elems: List[HtmlElement]) extends HtmlElement{ | |
| def print() = "DIV(["+ elems.map(_.print).mkString(", ") +"])" | |
| } | |
| case class P(elems: List[HtmlElement]) extends HtmlElement{ | |
| def print() = "P([" + elems.map(_.print).mkString(", ") +"])" | |
| } | |
| case class B(elems: List[HtmlElement]) extends HtmlElement{ | |
| def print() = "B([" + elems.map(_.print).mkString(", ") +"])" | |
| } | |
| case class Img() extends HtmlElement{ | |
| def print() = "IMG({})" | |
| } | |
| val easyToProcessHtml = html.replaceAll("<img />","i").replaceAll("</.{1,3}>","/").replaceAll("<div>","d").replaceAll("<p>","p").replaceAll("<b>","b") | |
| def getInnerHtml(string: List[Char]) = { | |
| def _getInnerHtml(str: List[Char], i: Int, retVal: List[Char]) : List[Char]={ | |
| if(i==0) {retVal.reverse} | |
| else{ | |
| str match { | |
| case '/'::tail => _getInnerHtml(tail,i-1,'/'+:retVal) | |
| case 'i'::tail => _getInnerHtml(tail,i,'i'+:retVal) | |
| case head::tail => _getInnerHtml(tail,i+1,head+:retVal) | |
| } | |
| } | |
| } | |
| _getInnerHtml(string,1,List()) | |
| } | |
| def processHtml(str: List[Char], retVal:List[HtmlElement]) : List[HtmlElement] = { | |
| str match { | |
| case Nil => | |
| retVal.reverse | |
| case '/'+:tail => | |
| processHtml(tail,retVal) | |
| case 'd'+:tail => | |
| val innerHtml = getInnerHtml(tail) | |
| processHtml(tail.drop(innerHtml.size),Div(processHtml(innerHtml,List()))+:retVal) | |
| case 'p'+:tail => | |
| val innerHtml = getInnerHtml(tail) | |
| processHtml(tail.drop(innerHtml.size),P(processHtml(innerHtml,List()))+:retVal) | |
| case 'b'+:tail => | |
| val innerHtml = getInnerHtml(tail) | |
| processHtml(tail.drop(innerHtml.size),B(processHtml(innerHtml,List()))+:retVal) | |
| case 'i'+:tail => | |
| processHtml(tail,Img()+:retVal) | |
| } | |
| } | |
| processHtml(easyToProcessHtml.toList,List()).map(_.print).mkString("") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment