Skip to content

Commit 7ab0db7

Browse files
committedApr 15, 2024
test cases passed
0 parents  commit 7ab0db7

8 files changed

+4182
-0
lines changed
 

‎.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/node_modules

‎__test__/cache.test.ts

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { BSTCache } from "../src/cache"
2+
// import { BSTCache } from 'keyache';
3+
4+
5+
describe('BSTCache', () => {
6+
let cache: BSTCache;
7+
8+
beforeEach(() => {
9+
cache = new BSTCache();
10+
});
11+
12+
it('should set and get values correctly', () => {
13+
cache.set('key1', 'value1');
14+
cache.set('key2', 'value2');
15+
16+
expect(cache.get('key1')).toBe('value1');
17+
expect(cache.get('key2')).toBe('value2');
18+
});
19+
20+
it('should return undefined for non-existent keys', () => {
21+
expect(cache.get('nonexistent')).toBeUndefined();
22+
});
23+
24+
it('should delete values correctly', () => {
25+
cache.set('key1', 'value1');
26+
cache.delete('key1');
27+
28+
expect(cache.get('key1')).toBeUndefined();
29+
});
30+
31+
it('should clear the cache correctly', () => {
32+
cache.set('key1', 'value1');
33+
cache.set('key2', 'value2');
34+
cache.clear();
35+
36+
expect(cache.get('key1')).toBeUndefined();
37+
expect(cache.get('key2')).toBeUndefined();
38+
});
39+
});

‎jest.config.ts

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
moduleNameMapper: {
5+
'^keyache$': '<rootDir>/dist/index.js',
6+
'^keyache/(.*)$': '<rootDir>/dist/$1',
7+
},
8+
};

‎package-lock.json

+3,824
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{
2+
"name": "keyache",
3+
"version": "1.0.0",
4+
"description": "A caching layer to speed up the API responses.",
5+
"main": "dist/index.js",
6+
"types": "dist/index.d.ts",
7+
"outDir": "./dist",
8+
"scripts": {
9+
"test": "jest"
10+
},
11+
"repository": {
12+
"type": "git",
13+
"url": "git+https://github.com/Devkant21/keyache.git"
14+
},
15+
"keywords": [
16+
"cache"
17+
],
18+
"author": "Devkant Swargiary",
19+
"license": "MIT",
20+
"bugs": {
21+
"url": "https://github.com/Devkant21/keyache/issues"
22+
},
23+
"homepage": "https://github.com/Devkant21/keyache#readme",
24+
"devDependencies": {
25+
"@types/jest": "^29.5.12",
26+
"@types/node": "^20.12.7",
27+
"jest": "^29.7.0",
28+
"ts-jest": "^29.1.2",
29+
"ts-node": "^10.9.2",
30+
"typescript": "^5.4.5"
31+
}
32+
}

‎src/cache.ts

+130
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// Node class for BST
2+
class Node {
3+
public key: string;
4+
public value: any;
5+
public left: Node | null;
6+
public right: Node | null;
7+
8+
constructor(key: string, value: any) {
9+
this.key = key;
10+
this.value = value;
11+
this.left = null;
12+
this.right = null;
13+
}
14+
}
15+
16+
// Binary Search Tree class
17+
class BinarySearchTree {
18+
private root: Node | null;
19+
20+
constructor() {
21+
this.root = null;
22+
}
23+
24+
insert(key: string, value: any): void {
25+
this.root = this.insertRec(this.root, key, value);
26+
}
27+
28+
private insertRec(node: Node | null, key: string, value: any): Node {
29+
if (node === null) {
30+
return new Node(key, value);
31+
}
32+
33+
if (key < node.key) {
34+
node.left = this.insertRec(node.left, key, value);
35+
} else if (key > node.key) {
36+
node.right = this.insertRec(node.right, key, value);
37+
} else {
38+
node.value = value;
39+
}
40+
41+
return node;
42+
}
43+
44+
search(key: string): any | undefined {
45+
return this.searchRec(this.root, key);
46+
}
47+
48+
private searchRec(node: Node | null, key: string): any | undefined {
49+
if (node === null) {
50+
return undefined;
51+
}
52+
53+
if (key < node.key) {
54+
return this.searchRec(node.left, key);
55+
} else if (key > node.key) {
56+
return this.searchRec(node.right, key);
57+
} else {
58+
return node.value;
59+
}
60+
}
61+
62+
delete(key: string): void {
63+
this.root = this.deleteRec(this.root, key);
64+
}
65+
66+
private deleteRec(node: Node | null, key: string): Node | null {
67+
if (node === null) {
68+
return null;
69+
}
70+
71+
if (key < node.key) {
72+
node.left = this.deleteRec(node.left, key);
73+
} else if (key > node.key) {
74+
node.right = this.deleteRec(node.right, key);
75+
} else {
76+
if (node.left === null && node.right === null) {
77+
return null;
78+
} else if (node.left === null) {
79+
return node.right;
80+
} else if (node.right === null) {
81+
return node.left;
82+
} else {
83+
const minNode = this.findMinNode(node.right);
84+
node.key = minNode.key;
85+
node.value = minNode.value;
86+
node.right = this.deleteRec(node.right, minNode.key);
87+
}
88+
}
89+
90+
return node;
91+
}
92+
93+
private findMinNode(node: Node): Node {
94+
while (node.left !== null) {
95+
node = node.left;
96+
}
97+
return node;
98+
}
99+
100+
clear(): void {
101+
this.root = null;
102+
}
103+
}
104+
105+
// Cache class using Binary Search Tree
106+
export class BSTCache {
107+
private bst: BinarySearchTree;
108+
109+
constructor() {
110+
this.bst = new BinarySearchTree();
111+
}
112+
113+
set(key: string, value: any): void {
114+
this.bst.insert(key, value);
115+
}
116+
117+
get(key: string): any | undefined {
118+
return this.bst.search(key);
119+
}
120+
121+
delete(key: string): void {
122+
this.bst.delete(key);
123+
}
124+
125+
clear(): void {
126+
this.bst.clear();
127+
}
128+
}
129+
130+

‎tsconfig.json

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
// "jsx": "preserve", /* Specify what JSX code is generated. */
17+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26+
27+
/* Modules */
28+
"module": "commonjs", /* Specify what module code is generated. */
29+
// "rootDir": "./", /* Specify the root folder within your source files. */
30+
"moduleResolution": "node10",
31+
"allowSyntheticDefaultImports": true, /* Specify how TypeScript looks up a file from a given module specifier. */
32+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
37+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
41+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
42+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
43+
// "resolveJsonModule": true, /* Enable importing .json files. */
44+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
45+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
46+
47+
/* JavaScript Support */
48+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
49+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
50+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
51+
52+
/* Emit */
53+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
54+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
55+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
56+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
57+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
58+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
59+
// "outDir": "./", /* Specify an output folder for all emitted files. */
60+
// "removeComments": true, /* Disable emitting comments. */
61+
// "noEmit": true, /* Disable emitting files from a compilation. */
62+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
63+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
64+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
65+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
66+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
67+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
68+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
69+
// "newLine": "crlf", /* Set the newline character for emitting files. */
70+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
71+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
72+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
73+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
74+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
75+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
76+
77+
/* Interop Constraints */
78+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
81+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
82+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
83+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
84+
85+
/* Type Checking */
86+
"strict": true, /* Enable all strict type-checking options. */
87+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
88+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
89+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
90+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
91+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
92+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
93+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
94+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
95+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
96+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
97+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
98+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
99+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
100+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
101+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
102+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
103+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
104+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
105+
106+
/* Completeness */
107+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
108+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
109+
}
110+
}

‎types/index.d.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// types/index.d.ts
2+
3+
declare module 'keyache' {
4+
import { BSTCache } from './cache';
5+
6+
export const cache: BSTCache;
7+
}
8+
9+
declare class Node {
10+
public key: string;
11+
public value: any;
12+
public left: Node | null;
13+
public right: Node | null;
14+
15+
constructor(key: string, value: any);
16+
}
17+
18+
declare class BinarySearchTree {
19+
private root: Node | null;
20+
21+
constructor();
22+
23+
insert(key: string, value: any): void;
24+
search(key: string): any | undefined;
25+
delete(key: string): void;
26+
clear(): void;
27+
}
28+
29+
declare class BSTCache {
30+
private bst: BinarySearchTree;
31+
32+
constructor();
33+
34+
set(key: string, value: any): void;
35+
get(key: string): any | undefined;
36+
delete(key: string): void;
37+
clear(): void;
38+
}

0 commit comments

Comments
 (0)
Please sign in to comment.