Skip to content

Commit 507ea54

Browse files
authored
Create getTimeComplexity.js
1 parent da95b17 commit 507ea54

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

05-Algorithms/getTimeComplexity.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
function getTimeComplexity(fn) {
2+
let loopCount = 0;
3+
let recurseCount = 0;
4+
5+
function countLoops(node) {
6+
if (node.type === 'WhileStatement' || node.type === 'ForStatement' || node.type === 'DoWhileStatement') {
7+
loopCount++;
8+
}
9+
if (node.body) {
10+
if (Array.isArray(node.body)) {
11+
node.body.forEach(countLoops);
12+
} else {
13+
countLoops(node.body);
14+
}
15+
}
16+
}
17+
18+
function countRecurses(node) {
19+
if (node.type === 'CallExpression' && node.callee.name === fn.name) {
20+
recurseCount++;
21+
}
22+
if (node.arguments) {
23+
node.arguments.forEach(countRecurses);
24+
}
25+
if (node.body) {
26+
if (Array.isArray(node.body)) {
27+
node.body.forEach(countRecurses);
28+
} else {
29+
countRecurses(node.body);
30+
}
31+
}
32+
}
33+
34+
const ast = esprima.parseScript(fn.toString());
35+
console.log('AST:', ast);
36+
countLoops(ast);
37+
countRecurses(ast);
38+
console.log('Loop count:', loopCount);
39+
console.log('Recursion count:', recurseCount);
40+
41+
if (recurseCount > 0) {
42+
console.log('Time complexity: Exponential');
43+
return 'Exponential';
44+
} else if (loopCount > 0) {
45+
if (loopCount === 1) {
46+
console.log('Time complexity: Linear');
47+
return 'Linear';
48+
} else if (loopCount === 2) {
49+
console.log('Time complexity: Quadratic');
50+
return 'Quadratic';
51+
} else {
52+
console.log('Time complexity: Polynomial');
53+
return 'Polynomial';
54+
}
55+
} else {
56+
console.log('Time complexity: Constant');
57+
return 'Constant';
58+
}
59+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy