1
+ package com .github .sonenko .scalajs .samples .validatebracesinstring
2
+
3
+ import scala .scalajs .js
4
+ import org .scalajs .jquery ._
5
+ import js .Dynamic .{ global => g }
6
+
7
+ object SampleStringValidator {
8
+ def init (): Unit = {
9
+ jQuery(" #validate-braces-in-string" ).click{onClick _}
10
+
11
+ def onClick (): Unit = {
12
+ val str = g.prompt(" enter string to test" , """ var a = {"a": ["hello", "world", function(){}]}""" ).toString
13
+ g.alert(check(str))
14
+ }
15
+ }
16
+
17
+ /**
18
+ * checks if str valid line for IDE(for example)
19
+ * "{}" => true
20
+ * "}{" => false
21
+ * "[{]}" => false
22
+ */
23
+ def check (str : String ): Boolean = {
24
+ val opposite : Map [Char , Char ] = Map ('{' -> '}' , '(' -> ')' , '[' -> ']' )
25
+ def doCheck (str : List [Char ], expected : List [Char ]): Boolean = (str, expected) match {
26
+ case (Nil , exp) => exp.length == 0
27
+ case ((x@ ('{' | '[' | '(' )) :: xs, e) => doCheck(xs, opposite(x) :: e)
28
+ case (('}' | ']' | ')' ) :: xs, Nil ) => false
29
+ case ((x@ ('}' | ']' | ')' )) :: xs, eHead :: eTail) => x == eHead && doCheck(xs, eTail)
30
+ case (_ :: xs, e) => doCheck(xs.toList, e)
31
+ }
32
+ doCheck(str.toList, Nil )
33
+ }
34
+
35
+ /**
36
+ * --- pure JS realization example
37
+ * function check(str) {
38
+ * var enters = ['{', '(', '['],
39
+ * exits = ['}', ')', ']'],
40
+ * opposite = (function(){
41
+ * var res = {}, i = 0;
42
+ * for (; i < enters.length; i++) { res[enters[i]] = exits[i]; }
43
+ * return res;
44
+ * }()),
45
+ * expected = [],
46
+ * key = null,
47
+ * char = null;
48
+ *
49
+ * for (key in str) {
50
+ * char = str[key];
51
+ * if (enters.indexOf(char) >= 0) {
52
+ * expected.unshift(opposite[char]);
53
+ * } else if (exits.indexOf(char) >= 0) {
54
+ * if (expected.length === 0 || char != expected[0]) return false;
55
+ * else expected.shift();
56
+ * }
57
+ * }
58
+ *
59
+ * return true;
60
+ * }
61
+ */
62
+ def checkInLoop (str : String ): Boolean = {
63
+ val opposite : Map [Char , Char ] = Map ('{' -> '}' , '(' -> ')' , '[' -> ']' )
64
+ var expected : List [Char ] = Nil
65
+ for { x <- str} {
66
+ (x, expected) match {
67
+ case ('{' | '[' | '(' , e) => expected = opposite(x) :: expected
68
+ case ('}' | ']' | ')' , Nil ) => return false
69
+ case ('}' | ']' | ')' , eHead :: eTail) if x != eHead => return false
70
+ case ('}' | ']' | ')' , eHead :: eTail) => expected = eTail
71
+ case _ =>
72
+ }
73
+ }
74
+ true
75
+ }
76
+ }
0 commit comments