My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/**
* ...
* @author Franco Ponticelli
*/

import thx.culture.Culture;
import thx.error.Error;
import thx.culture.FormatParams;
using StringTools;
using Arrays;

class Strings
{
static var _re = new EReg("[{](\\d+)(?::[^}]*)?[}]", "m");
static var _reSplitWC = ~/(\r\n|\n\r|\n|\r)/g;
static var _reReduceWS = ~/\s+/;
#if !php
static var _reStripTags = ~/(<[a-z]+[^>\/]*\/?>|<\/[a-z]+>)/i;
#end

static var _reFormat = ~/{(\d+)(?::([a-zA-Z]+))?(?:,([^"',}]+|'[^']+'|"[^"]+"))?(?:,([^"',}]+|'[^']+'|"[^"]+"))?(?:,([^"',}]+|'[^']+'|"[^"]+"))?}/m;
/**
* Take a string pattern and replaces the placeholders with the value contained in values.
* The culture parameter is needed for proper localization of numeric and date values.
* Placeholders follows this schema:
<pre>
{pos[:format][,param]*}
</pre>
* <em>pos</em> is the position in the array
* <em>format</em> is a string sequence that identifies a specific value format (see below)
* <em>param</em> is one or more optional parameters specific to certain format values.
*
* <pre>
Numeric Formats
---------------
D (default) Decimal format. The default number of decimals is set by culture. This value can overriden
using the length parameter.
I Integer format.
C Currency format. The default number of decimals is set by culture. This value can overriden
using the length parameter. The symbol can be overridden appending a string value after C
Ei. "{0:C,3,USD}" will print something like "USD2.000" instead of "$2.00"
P Percent format.
M Permille format.

Date Formats
---------------
D (default) Date format.
DS Short Date format.
DST Short date / long time format.
DSTS Short date / short time format.
DT Long date / long time format.
DTS Long date / short time format.
Y Year format.
YM Year Month format.
M Month format.
MN Month name format.
MS Short Month name format.
MD Month Day format.
WD Week day format.
WDN Week day name format.
WDS Short week day name format.
R RFC Date format.
DT Date Time format.
U Universal format.
S Sortable format.
T Time format.
TS Short Time format.
C Custom, second parameter is the format as described in FormatDate

Boolean Formats
---------------
B Normal bool (true, false)
N Numeric representation (1, 0)
R Replace values with first parameter for true and second for false

String Formats
---------------
S Normal text.
T Truncate. First parameter is the length to trim, second is the ellipsis
(optional parameter, defaults to '...')
PL Pad left. First parameter is the length, second is filling char
(optional parameter, defaults to ' ')
PR Pad right. First parameter is the length, second is filling char
(optional parameter, defaults to ' ')

List Formats
---------------
J Joins the elements of the list.
The first parameter is the format for individual items
The second parameter is what is shown when the list is empty (defaults to '[]')
The third is the separator.
The fourth is the maximum number of values to show (default to nolimit).
The fifth parameter the ellipsis for not included values (defaults to '...'),
C Counts the elements in the list

Object Formats
----------------
O Uses the Std.string function
R Uses the Reflects.string function for each field value

TODO:
List Formats
---------------
C Concats the elements of the list

Other things to do. Nested placeholders
</pre>
*/
public static function format(pattern : String, values : Array<Dynamic>, nullstring = 'null', ?culture : Culture) {
if (null == values || 0 == values.length)
return pattern;
return formatf(pattern, nullstring, culture)(values);
}

public static function formatf(pattern : String, nullstring = 'null', ?culture : Culture)
{
var buf = [];
while (true)
{
if (!_reFormat.match(pattern))
{
buf.push(function(_) return pattern);
break;
}

var pos = Std.parseInt(_reFormat.matched(1));
var format = _reFormat.matched(2);
if (format == '') // '' is for IE
format = null;
var p = null;
var params = [];
for (i in 3...20) // 20 is a guard limit, 5 is probably more than enough
{
p = _reFormat.matched(i);
if(p == null || p == '') // again IE
break;
params.push(FormatParams.cleanQuotes(p));
}
var left = _reFormat.matchedLeft();
buf.push(function(_) return left);
var df = Dynamics.formatf(format, params, nullstring, culture);
buf.push(callback(function(i : Int, v : Array<Dynamic>) return df(v[i]), pos));
pattern = _reFormat.matchedRight();
}
return function(values : Array<Dynamic>)
{
if (null == values)
values = [];
return buf.map(function(df,_) return df(values)).join("");
}
}

public static function formatOne(v : String, ?param : String, ?params : Array<String>, ?culture : Culture)
{
return formatOnef(param, params, culture)(v);
}

public static function formatOnef(?param : String, ?params : Array<String>, ?culture : Culture)
{
params = FormatParams.params(param, params, 'S');
var format = params.shift();
switch(format)
{
case 'S':
return function(v : String) return v;
case 'T':
var len = params.length < 1 ? 20 : Std.parseInt(params[0]);
var ellipsis = params.length < 2 ? "..." : params[1];
return ellipsisf(len, ellipsis);
case 'PR':
var len = params.length < 1 ? 10 : Std.parseInt(params[0]);
var pad = params.length < 2 ? " " : params[1];
return function(v : String) return StringTools.rpad(v, pad, len);
case 'PL':
var len = params.length < 1 ? 10 : Std.parseInt(params[0]);
var pad = params.length < 2 ? " " : params[1];
return function(v : String) return StringTools.lpad(v, pad, len);
default:
return throw "Unsupported string format: " + format;
}
}

// TODO, test me
public static function upTo(value : String, searchFor : String)
{
var pos = value.indexOf(searchFor);
if (pos < 0)
return value;
else
return value.substr(0, pos);
}

// TODO, test me
public static function startFrom(value : String, searchFor : String)
{
var pos = value.indexOf(searchFor);
if (pos < 0)
return value;
else
return value.substr(pos + searchFor.length);
}

// TODO, test me
public static function rtrim(value : String, charlist : String) : String
{
#if php
return untyped __call__("rtrim", value, charlist);
#else
var len = value.length;
while (len > 0)
{
var c = value.substr(len - 1, 1);
if (charlist.indexOf(c) < 0)
break;
len--;
}
return value.substr(0, len);
#end
}

// TODO, test me
public static function ltrim(value : String, charlist : String) : String
{
#if php
return untyped __call__("ltrim", value, charlist);
#else
var start = 0;
while (start < value.length)
{
var c = value.substr(start, 1);
if (charlist.indexOf(c) < 0)
break;
start++;
}
return value.substr(start);
#end
}

public static inline function trim(value : String, charlist : String) : String
{
#if php
return untyped __call__("trim", value, charlist);
#else
return rtrim(ltrim(value, charlist), charlist);
#end
}

static var _reCollapse = ~/\s+/g;
public static function collapse(value : String)
{
return _reCollapse.replace(StringTools.trim(value), " ");
}

public static inline function ucfirst(value : String) : String
{
return (value == null ? null : value.charAt(0).toUpperCase() + value.substr(1));
}

public static inline function lcfirst(value : String) : String
{
return (value == null ? null : value.charAt(0).toLowerCase() + value.substr(1));
}

public static function empty(value : String)
{
return value == null || value == '';
}

public static inline function isAlphaNum(value : String) : Bool
{
#if php
return untyped __call__("ctype_alnum", value);
#else
return (value == null ? false : __alphaNumPattern.match(value));
#end
}

public static inline function digitsOnly(value : String) : Bool
{
#if php
return untyped __call__("ctype_digit", value);
#else
return (value == null ? false : __digitsPattern.match(value));
#end
}

public static function ucwords(value : String) : String
{
return __ucwordsPattern.customReplace(ucfirst(value), __upperMatch);
}

/**
* Like ucwords but uses only white spaces as boundaries
* @param value
* @return
*/
public static function ucwordsws(value : String) : String
{
#if php
return untyped __call__("ucwords", value);
#else
return __ucwordswsPattern.customReplace(ucfirst(value), __upperMatch);
#end
}

static function __upperMatch(re : EReg)
{
return re.matched(0).toUpperCase();
}
static var __ucwordsPattern = new EReg('[^a-zA-Z]([a-z])', '');
#if !php
static var __ucwordswsPattern = new EReg('\\s([a-z])', '');
static var __alphaNumPattern = new EReg('^[a-z0-9]+$', 'i');
static var __digitsPattern = new EReg('^[0-9]+$', '');
#end

/**
* Replaces undescores with space, finds UC characters, turns them into LC and prepends them with a space.
* More than one UC in sequence is left untouched.
**/
public static function humanize(s : String)
{
return underscore(s).replace('_', ' ');
}

// TO TEST
public static function capitalize(s : String)
{
return s.substr(0, 1).toUpperCase() + s.substr(1);
}

// TO TEST
public static function succ(s : String)
{
return s.substr(0, -1) + String.fromCharCode(s.substr(-1).charCodeAt(0)+1);
}

// TO TEST
public static function underscore(s : String)
{
s = (~/::/g).replace(s, '/');
s = (~/([A-Z]+)([A-Z][a-z])/g).replace(s, '$1_$2');
s = (~/([a-z\d])([A-Z])/g).replace(s, '$1_$2');
s = (~/-/g).replace(s, '_');
return s.toLowerCase();
}

public static function dasherize(s : String)
{
return s.replace('_', '-');
}

public static function repeat(s : String, times : Int)
{
var b = [];
for(i in 0...times)
b.push(s);
return b.join('');
}

public static function wrapColumns(s : String, columns = 78, indent = "", newline = "\n")
{
var parts = _reSplitWC.split(s);
var result = [];
for(part in parts)
{
result.push(_wrapColumns(StringTools.trim(_reReduceWS.replace(part, " ")), columns, indent, newline));
}
return result.join(newline);
}

static function _wrapColumns(s : String, columns : Int, indent : String, newline : String)
{
var parts = [];
var pos = 0;
var len = s.length;
var ilen = indent.length;
columns -= ilen;
while(true)
{
if(pos + columns >= len - ilen)
{
parts.push(s.substr(pos));
break;
}

var i = 0;
while(!StringTools.isSpace(s, pos + columns - i) && i < columns)
{
i++;
}
if(i == columns)
{
// search ahead
i = 0;
while(!StringTools.isSpace(s, pos + columns + i) && pos + columns + i < len)
{
i++;
}
parts.push(s.substr(pos, columns + i));
pos += columns + i + 1;
} else {
parts.push(s.substr(pos, columns - i));
pos += columns - i + 1;
}
}

return indent + parts.join(newline + indent);
}

public static function stripTags(s : String) : String
{
#if php
return untyped __call__("strip_tags", s);
#else
return _reStripTags.replace(s, "");
#end
}

static var _reInterpolateNumber = ~/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/;
public static function interpolate(v : Float, a : String, b : String, ?equation : Float -> Float)
{
return interpolatef(a, b, equation)(v);
}

public static function interpolatef(a : String, b : String, ?equation : Float -> Float)
{
function extract(value : String, s : Array<String>, f : Array<Null<Float>>)
{
while (_reInterpolateNumber.match(value))
{
var left = _reInterpolateNumber.matchedLeft();
if (!Strings.empty(left))
{
s.push(left);
f.push(null);
}
s.push(null);
f.push(Std.parseFloat(_reInterpolateNumber.matched(0)));
value = _reInterpolateNumber.matchedRight();
}
if (!Strings.empty(value))
{
s.push(value);
f.push(null);
}
}
var sa = [],
fa = [],
sb = [],
fb = [];
extract(a, sa, fa);
extract(b, sb, fb);

var functions = [], i = 0;
var min = Ints.min(sa.length, sb.length);
while (i < min)
{
if (sa[i] != sb[i])
break;
if (null == sa[i])
{
if (fa[i] == fb[i]) // no need to interpolate
{
var s = "" + fa[i];
functions.push(function(_) return s);
} else {
var f = Floats.interpolatef(fa[i], fb[i], equation);
functions.push(function(t) return "" + f(t));
}
} else {
var s = sa[i];
functions.push(function(_) return s);
}
i++;
}
var rest = "";
while (i < sb.length)
{
if (null != sb[i])
rest += sb[i];
else
rest += fb[i];
i++;
}
if ("" != rest)
functions.push(function(_) return rest);
return function(t) {
return Arrays.map(functions, function(f,_) return f(t)).join("");
};
}

public static function interpolateChars(v : Float, a : String, b : String, ?equation : Float -> Float)
{
return interpolateCharsf(a, b, equation)(v);
}

public static function interpolateCharsf(a : String, b : String, ?equation : Float -> Float) : Float -> String
{
var aa = a.split(""),
ab = b.split("");
while (aa.length > ab.length)
ab.insert(0, " ");
while (ab.length > aa.length)
aa.insert(0, " ");
var ai = [];
for (i in 0...aa.length)
ai[i] = interpolateCharf(aa[i], ab[i]);
return function(v)
{
var r = [];
for (i in 0...ai.length)
r[i] = ai[i](v);
return StringTools.trim(r.join(""));
}
}

public static function interpolateChar(v : Float, a : String, b : String, ?equation : Float -> Float)
{
return interpolateCharf(a, b, equation)(v);
}

public static function interpolateCharf(a : String, b : String, ?equation : Float -> Float) : Float -> String
{
var ca = a.charCodeAt(0),
cb = b.charCodeAt(0),
i = Ints.interpolatef(ca, cb, equation);
return function(v) return String.fromCharCode(i(v));
}

public static function ellipsis(s : String, maxlen = 20, symbol = "...")
{
if (s.length > maxlen)
return s.substr(0, Ints.max(symbol.length, maxlen - symbol.length)) + symbol;
else
return s;
}

public static function ellipsisf(maxlen = 20, symbol = "...")
{
return function(s : String)
{
if (s.length > maxlen)
return s.substr(0, Ints.max(symbol.length, maxlen - symbol.length)) + symbol;
else
return s;
}
}

public static function compare(a : String, b : String) return a < b ? -1 : a > b ? 1 : 0
}

Change log

7cf208bc5824 by franco.ponticelli on Aug 10, 2011   Diff
added Arrays.rotate
added Strings.interpolateChar/Strings.inte
rpolateChars
added AccessClassed.toggle
added transition on chars
fixed bug for jQuery dependency
added Transition.text
added Symbol.star
Go to: 
Project members, sign in to write a code review

Older revisions

80cbf9e2be2f by franco.ponticelli on Jul 20, 2011   Diff
minor fixes
added Objects.format
added level parameter (optional) to
Objects.flatten
added length to Set
...
28339b667b09 by franco.ponticelli on Jun 21, 2011   Diff
fixed:
 * bug in time format (FormatDate)
 * perfomance issues in JsonDecoder
features:
 * LinearTime now allows to pick a
...
d966809f2a69 by franco.ponticelli on May 28, 2011   Diff
Arrays
  bug fixing
Arrays/Iterables/Iterators
  added fristf/lastf
Dates
...
All revisions of this file

File info

Size: 14674 bytes, 551 lines
Powered by Google Project Hosting