forked from electricessence/TypeScript.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.ts
More file actions
94 lines (71 loc) · 1.8 KB
/
Copy pathUtility.ts
File metadata and controls
94 lines (71 loc) · 1.8 KB
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
/*
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
*/
///<reference path="ISerializable.d.ts"/>
///<reference path="../Primitive.d.ts"/>
import Type from '../Types';
import InvalidOperationException from '../Exceptions/InvalidOperationException';
const EMPTY = '', TRUE = 'true', FALSE = 'false';
export function toString(
value:Primitive|ISerializable,
defaultForUnknown?:string):string
{
var v = <any>value;
switch(typeof v)
{
case Type.NULL:
case Type.UNDEFINED:
case Type.STRING:
return v;
case Type.BOOLEAN:
return v ? TRUE : FALSE;
case Type.NUMBER:
return EMPTY + v;
default:
if(Type.of(v).member('serialize').isFunction)
return v.serialize();
else if(arguments.length>1)
return defaultForUnknown;
var ex = new InvalidOperationException('Attempting to serialize unidentifiable type.');
ex.data['value'] = v;
throw ex;
}
}
export function toPrimitive(
value:string,
caseInsensitive?:boolean,
unknownHandler?:(v:string)=>string):Primitive
{
if(value)
{
if(caseInsensitive) value = value.toLowerCase();
switch(value)
{
case Type.NULL:
return null;
case Type.UNDEFINED:
return undefined;
case TRUE:
return true;
case FALSE:
return false;
default:
var cleaned = value.replace(/^\s+|,|\s+$/g,EMPTY);
if(cleaned) {
if(/^\d+$/g.test(cleaned)) {
var int = parseInt(cleaned);
if(!isNaN(int)) return int;
} else {
var number = parseFloat(value);
if(!isNaN(number)) return number;
}
}
// TODO: Handle Dates... Possibly JSON?
// Instead of throwing we allow for handling...
if(unknownHandler) value = unknownHandler(value);
break;
}
}
return value;
}