-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountArgumentsLib.js
More file actions
61 lines (56 loc) · 2.62 KB
/
CountArgumentsLib.js
File metadata and controls
61 lines (56 loc) · 2.62 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
export default fnLenFactory();
function fnLenFactory() {
const {extractArgs, valueParamsCleanup, cleanupFnStr} = regExps();
const countArgumentsByBrackets = params => {
let [commaCount, bracketCount, bOpen, bClose] = [0, 0, [...`([{`], [...`)]}`]];
[...params].forEach( chr => {
bracketCount += bOpen.includes(chr) ? 1 : bClose.includes(chr) ? -1 : 0;
commaCount += chr === ',' && bracketCount === 1 ? 1 : 0; } );
return commaCount + 1; };
const extractArgumentsPartFromFunction = fn => {
let fnStr = `${fn}`.replace(cleanupFnStr(fn.name), ``);
fnStr = fnStr.match(extractArgs).shift().replace(/[\\]./g, ``).replace(valueParamsCleanup, ``);
return !fnStr.startsWith(`(`) ? `(${fnStr})` : fnStr; };
return func => {
const params = extractArgumentsPartFromFunction(func);
const nParams = params === `()` ? 0 : countArgumentsByBrackets(params);
return nParams;
};
function regExps() {
return {
extractArgs: createRegExp`
// Retriever arguments from a cleaned stringified function
// ---
( ^[a-z_]( ?=(=>|=>{) ) ) // letter or underscore followed by fat arrow and/or curly opening bracket
| ( ( (^\([^)].+\) ) // or anything between parenthesis
| \(\) ) // or parenthesis open + close
( ?=( =>|=>{|{ ) ) ) // followed by =>, =>{ or {
${[`i`]} // case insensitive`,
valueParamsCleanup: createRegExp`
// Cleanup arguments /w default string values
// ---
( ?<=[\`"'] ) // everything prefixed with string delimiter
( [^\`,'"].+? ) // everything thereafter except starting delimiters *and comma* (non greedy)
( ?=[\`"'] ) // followed by starting string delimiter
${[`g`]} // global`,
cleanupFnStr: name => createRegExp`
// For cleanup of a stringified [named] Function.
// matches replaced with empty string will result in a string
// without spaces and starting with the function parameters
// ---
\s // space
| function // 'function'
| ${name} // the function name
${[`g`]} // global`, };
}
function createRegExp(regexStr, ...args) {
const flags = Array.isArray(args.slice(-1)) ? args.pop().join('') : ``;
return new RegExp(
(args.length &&
regexStr.raw.reduce( (a, v, i ) => a.concat(args[i-1] || ``).concat(v), ``) ||
regexStr.raw.join(``))
.split(`\n`)
.map( line => line.replace(/\s|\/\/.*$/g, ``).trim().replace(/@s/g, ` `) )
.join(``), flags );
}
}