comparison src/implab/text/format.js @ 34:27e8e9e38e07 default tip

Слияние
author nickolay
date Wed, 05 Jun 2019 20:44:15 +0300
parents 8af8e840dd49 1dc2fd263b90
children
comparison
equal deleted inserted replaced
33:8af8e840dd49 34:27e8e9e38e07
1 define([
2 "../safe",
3 "./format-compile",
4 "dojo/number",
5 "dojo/date/locale",
6 "dojo/_base/array" ], function(safe, compile, number, date, array) {
7
8 // {short,medium,full,long}-{date,time}
9 var convert = function(value, pattern) {
10 if (!pattern)
11 return value.toString();
12
13 if (pattern.toLocaleLowerCase() == "json") {
14 var cache = [];
15 return JSON.stringify(value, function(k, v) {
16 if (!safe.isPrimitive(v)) {
17 var id = array.indexOf(cache, v);
18 if (id >= 0)
19 return "@ref-" + id;
20 else
21 return v;
22 } else {
23 return v;
24 }
25 },2);
26 }
27
28 if (safe.isNumber(value)) {
29 var nopt = {};
30 if (pattern.indexOf("!") === 0) {
31 nopt.round = -1;
32 pattern = pattern.substr(1);
33 }
34 nopt.pattern = pattern;
35 return number.format(value, nopt);
36 } else if (value instanceof Date) {
37 var m = pattern.match(/^(\w+)-(\w+)$/);
38 if (m)
39 return date.format(value, {
40 selector : m[2],
41 formatLength : m[1]
42 });
43 else if (pattern == "iso")
44 return value.toISOString();
45 else
46 return date.format(value, {
47 selector : "date",
48 datePattern : pattern
49 });
50 } else {
51 return value.toString(pattern);
52 }
53 };
54
55 function formatter(format) {
56 var data;
57
58 if (arguments.length <= 1)
59 return format;
60
61 data = Array.prototype.slice.call(arguments, 1);
62
63 var template = compile(format);
64
65 return template(function(name, pattern) {
66 var value = data[name];
67 return !safe.isNull(value) ? convert(value, pattern) : "";
68 });
69 }
70
71 formatter.compile = function(format) {
72 var template = compile(format);
73
74 return function() {
75 var data = arguments;
76
77 return template(function(name, pattern) {
78 var value = data[name];
79 return !safe.isNull(value) ? convert(value, pattern) : "";
80 });
81 };
82 };
83
84 formatter.convert = convert;
85
86 return formatter;
87 });