-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
to-string-tokens.js
52 lines (46 loc) · 1.64 KB
/
to-string-tokens.js
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
"use strict";
var isValue = require("../../object/is-value")
, esniff = require("esniff")
, validFunction = require("../valid-function");
var classRe = /^\s*class[\s{/}]/;
module.exports = function () {
var str = String(validFunction(this));
if (classRe.test(str)) throw new Error("Class methods are not supported");
var argsStartIndex
, argsEndIndex
, bodyStartIndex
, bodyEndReverseIndex = -1
, shouldTrimArgs = false;
esniff(str, function (emitter, accessor) {
emitter.once("trigger:(", function () { argsStartIndex = accessor.index + 1; });
emitter.once("trigger:=", function () {
if (isValue(argsStartIndex)) return;
argsStartIndex = 0;
argsEndIndex = accessor.index;
shouldTrimArgs = true;
if (!accessor.skipCodePart("=>")) {
throw new Error("Unexpected function string: " + str);
}
accessor.skipWhitespace();
if (!accessor.skipCodePart("{")) bodyEndReverseIndex = Infinity;
bodyStartIndex = accessor.index;
});
emitter.on("trigger:)", function () {
if (accessor.scopeDepth) return;
argsEndIndex = accessor.index;
accessor.skipCodePart(")");
accessor.skipWhitespace();
if (accessor.skipCodePart("=>")) {
accessor.skipWhitespace();
if (!accessor.skipCodePart("{")) bodyEndReverseIndex = Infinity;
} else if (!accessor.skipCodePart("{")) {
throw new Error("Unexpected function string: " + str);
}
bodyStartIndex = accessor.index;
accessor.stop();
});
});
var argsString = str.slice(argsStartIndex, argsEndIndex);
if (shouldTrimArgs) argsString = argsString.trim();
return { args: argsString, body: str.slice(bodyStartIndex, bodyEndReverseIndex) };
};