on bb9ffcf help sign in
elk/libraries/Native/Regex.js
103 lines 3.0 kB history raw
1Elm.Native.Regex = {};
2Elm.Native.Regex.make = function(elm) {
3 elm.Native = elm.Native || {};
4 elm.Native.Regex = elm.Native.Regex || {};
5 if (elm.Native.Regex.values) return elm.Native.Regex.values;
6 if ('values' in Elm.Native.Regex)
7 return elm.Native.Regex.values = Elm.Native.Regex.values;
9 var List = Elm.Native.List.make(elm);
10 var Maybe = Elm.Maybe.make(elm);
12 function escape(str) {
13 return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
14 }
15 function caseInsensitive(re) {
16 return new RegExp(re.source, 'gi');
17 }
18 function regex(raw) {
19 return new RegExp(raw, 'g');
20 }
22 function contains(re, string) {
23 return string.match(re) !== null;
24 }
26 function find(n, re, str) {
27 n = n.ctor === "All" ? Infinity : n._0;
28 var out = [];
29 var number = 0;
30 var string = str;
31 var result;
32 while (number++ < n && (result = re.exec(string))) {
33 var i = result.length - 1;
34 var subs = new Array(i);
35 while (i > 0) {
36 var submatch = result[i];
37 subs[--i] = submatch === undefined
38 ? Maybe.Nothing
39 : Maybe.Just(submatch);
40 }
41 out.push({
42 _:{},
43 match: result[0],
44 submatches: List.fromArray(subs),
45 index: result.index,
46 number: number
47 });
48 }
49 return List.fromArray(out);
50 }
52 function replace(n, re, replacer, string) {
53 n = n.ctor === "All" ? Infinity : n._0;
54 var count = 0;
55 function jsReplacer(match) {
56 if (count++ > n) return match;
57 var i = arguments.length-3;
58 var submatches = new Array(i);
59 while (i > 0) {
60 var submatch = arguments[i];
61 submatches[--i] = submatch === undefined
62 ? Maybe.Nothing
63 : Maybe.Just(submatch);
64 }
65 return replacer({
66 _:{},
67 match:match,
68 submatches:List.fromArray(submatches),
69 index:arguments[i-1],
70 number:count
71 });
72 }
73 return string.replace(re, jsReplacer);
74 }
76 function split(n, re, str) {
77 if (n === Infinity) {
78 return List.fromArray(string.split(re));
79 }
80 var string = str;
81 var result;
82 var out = [];
83 var start = re.lastIndex;
84 while (n--) {
85 if (!(result = re.exec(string))) break;
86 out.push(string.slice(start, result.index));
87 start = re.lastIndex;
88 }
89 out.push(string.slice(start));
90 return List.fromArray(out);
91 }
93 return Elm.Native.Regex.values = {
94 regex: regex,
95 caseInsensitive: caseInsensitive,
96 escape: escape,
98 contains: F2(contains),
99 find: F3(find),
100 replace: F4(replace),
101 split: F3(split)
102 };
103};