├── README.md ├── binary-heap ├── heap.ts └── tsconfig.json ├── graph-traversal ├── bfs.ts ├── dfs.ts ├── graph.ts └── tsconfig.json ├── topological-sort ├── graph.ts ├── topological-sort.ts └── tsconfig.json └── tries └── index.js /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | Code samples from the "Programming" podcast. 6 | 7 | ## License 8 | 9 | MIT 10 | -------------------------------------------------------------------------------- /binary-heap/heap.ts: -------------------------------------------------------------------------------- 1 | export interface Comparator { 2 | (a: T, b: T): number; 3 | } 4 | 5 | const swap = (a: number, b: number, arr: T[]) => { 6 | const tmp = arr[a]; 7 | arr[a] = arr[b]; 8 | arr[b] = tmp; 9 | }; 10 | 11 | export class Heap { 12 | private _arr: T[] = []; 13 | constructor(private _comparator: Comparator) {} 14 | 15 | insert(el: T) { 16 | let idx = this._arr.length; 17 | this._arr.push(el); 18 | 19 | while (idx) { 20 | const parentIdx = Math.floor(idx / 2); 21 | if (this._comparator(el, this._arr[parentIdx]) < 0) { 22 | swap(parentIdx, idx, this._arr); 23 | idx = parentIdx; 24 | } else { 25 | return; 26 | } 27 | } 28 | } 29 | 30 | pop(): T | undefined { 31 | if (!this._arr.length) { 32 | return undefined; 33 | } 34 | swap(0, this._arr.length - 1, this._arr); 35 | const result = this._arr.pop(); 36 | this._heapify(0); 37 | return result; 38 | } 39 | 40 | top(): T | undefined { 41 | return this._arr[0]; 42 | } 43 | 44 | private _heapify(start: number) { 45 | const len = this._arr.length; 46 | if (start >= len) { 47 | return; 48 | } 49 | 50 | const left = 2 * start + 1; 51 | const right = 2 * start + 2; 52 | 53 | let futureParent = start; 54 | const startVal = this._arr[start]; 55 | 56 | if (left < len && this._comparator(this._arr[left], startVal) < 0) { 57 | futureParent = left; 58 | } 59 | 60 | if (right < len && 61 | (this._comparator(this._arr[right], startVal) < 0 && 62 | this._comparator(this._arr[right], this._arr[left]) < 0)) { 63 | futureParent = right; 64 | } 65 | 66 | if (futureParent !== start) { 67 | swap(start, futureParent, this._arr); 68 | this._heapify(futureParent); 69 | } 70 | } 71 | } 72 | 73 | const heap = new Heap((a, b) => a - b); 74 | heap.insert(5); 75 | console.log(heap.top()); 76 | 77 | heap.insert(6); 78 | console.log(heap.top()); 79 | 80 | heap.insert(1); 81 | console.log(heap.top()); 82 | 83 | heap.insert(8); 84 | console.log(heap.top()); 85 | 86 | heap.insert(-1); 87 | console.log(heap.top()); 88 | 89 | console.log(heap.pop()); 90 | console.log(heap.pop()); 91 | console.log(heap.pop()); 92 | console.log(heap.pop()); 93 | console.log(heap.pop()); 94 | console.log(heap.pop()); 95 | -------------------------------------------------------------------------------- /binary-heap/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | // "outDir": "./", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /graph-traversal/bfs.ts: -------------------------------------------------------------------------------- 1 | import { Node, node5, node1, node8 } from './graph'; 2 | 3 | // Does not handle loops 4 | const bfs = (start: Node) => { 5 | const queue: Node[] = [start]; 6 | while (queue.length) { 7 | const current = queue.shift()!; 8 | current.neighbors.forEach(n => queue.push(n)); 9 | } 10 | } 11 | 12 | // Keeps track of cycles in the graph 13 | const bfsWithCycle = (start: Node) => { 14 | const queue: Node[] = [start]; 15 | const visited = new Set([start]); 16 | while (queue.length) { 17 | const current = queue.shift()!; 18 | current.neighbors.forEach(n => { 19 | if (!visited.has(n)) { 20 | queue.push(n); 21 | visited.add(n); 22 | } 23 | }); 24 | } 25 | } 26 | 27 | // Keeps track of cycles in the graph 28 | const findShortestPath = (start: Node, dest: Node) => { 29 | const queue: Node[] = [start]; 30 | const visited = new Set([start]); 31 | const previous = new Map(); 32 | while (queue.length) { 33 | const current = queue.shift()!; 34 | current.neighbors.forEach(n => { 35 | if (!visited.has(n)) { 36 | previous.set(n, current); 37 | queue.push(n); 38 | visited.add(n); 39 | } 40 | }); 41 | } 42 | if (!previous.has(dest)) { 43 | return undefined; 44 | } 45 | const path = [dest]; 46 | let current = dest; 47 | while (current !== start) { 48 | current = previous.get(current)!; 49 | path.push(current); 50 | } 51 | return path.reverse(); 52 | } 53 | 54 | const path1_5 = findShortestPath(node1, node5); 55 | console.log('The shortest path between nodes #1 and #5 is', path1_5!.map(v => v.name).join(',')); 56 | 57 | const path1_8 = findShortestPath(node1, node8); 58 | console.assert(path1_8 === undefined); 59 | 60 | -------------------------------------------------------------------------------- /graph-traversal/dfs.ts: -------------------------------------------------------------------------------- 1 | import { Node, node0, node1, node2, node5, node6 } from "./graph"; 2 | 3 | const dfs = (start: Node) => { 4 | const stack: Node[] = [start]; 5 | while (stack.length) { 6 | const current = stack.pop()!; 7 | current.neighbors.forEach(n => stack.push(n)) 8 | } 9 | } 10 | 11 | // Keeps track of cycles in the graph 12 | // Keep in mind that this algorithm does not 13 | // find the shortest path. It just finds a path, 14 | // if such exists. 15 | const findPath = (start: Node, dest: Node) => { 16 | const stack: Node[] = [start]; 17 | const visited = new Set([start]); 18 | const previous = new Map(); 19 | while (stack.length) { 20 | const current = stack.pop()!; 21 | current.neighbors.forEach(n => { 22 | if (!visited.has(n)) { 23 | previous.set(n, current); 24 | stack.push(n); 25 | visited.add(n); 26 | } 27 | }); 28 | } 29 | if (!previous.has(dest)) { 30 | return undefined; 31 | } 32 | const path = [dest]; 33 | let current = dest; 34 | while (current !== start) { 35 | current = previous.get(current)!; 36 | path.push(current); 37 | } 38 | return path.reverse(); 39 | } 40 | 41 | const path1_5 = findPath(node1, node5); 42 | console.log('A path between nodes #1 and #5 is', path1_5!.map(v => v.name).join(',')); 43 | -------------------------------------------------------------------------------- /graph-traversal/graph.ts: -------------------------------------------------------------------------------- 1 | export interface Node { 2 | name: string; 3 | neighbors: Node[]; 4 | } 5 | 6 | 7 | /* 8 | 9 | Sample graph to operate over. 10 | 11 | 1 12 | / \ 13 | 2 3 14 | / \ 15 | 0 4 16 | | | 17 | | 6 8-7 18 | \ / 19 | 5 20 | 21 | */ 22 | 23 | export const node0: Node = { 24 | name: '0', 25 | neighbors: [] 26 | }; 27 | 28 | export const node1: Node = { 29 | name: '1', 30 | neighbors: [] 31 | }; 32 | 33 | export const node2: Node = { 34 | name: '2', 35 | neighbors: [] 36 | }; 37 | 38 | export const node3: Node = { 39 | name: '3', 40 | neighbors: [] 41 | }; 42 | 43 | export const node4: Node = { 44 | name: '4', 45 | neighbors: [] 46 | }; 47 | 48 | export const node5: Node = { 49 | name: '5', 50 | neighbors: [] 51 | }; 52 | 53 | export const node6: Node = { 54 | name: '6', 55 | neighbors: [] 56 | }; 57 | 58 | export const node7: Node = { 59 | name: '7', 60 | neighbors: [] 61 | }; 62 | 63 | export const node8: Node = { 64 | name: '8', 65 | neighbors: [] 66 | }; 67 | 68 | node0.neighbors.push(node3, node5); 69 | node1.neighbors.push(node2, node3); 70 | node2.neighbors.push(node1); 71 | node3.neighbors.push(node0, node4); 72 | node4.neighbors.push(node3, node6); 73 | node5.neighbors.push(node0, node4); 74 | node6.neighbors.push(node4, node5); 75 | 76 | node7.neighbors.push(node8); 77 | node8.neighbors.push(node7); 78 | -------------------------------------------------------------------------------- /graph-traversal/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | // "outDir": "./", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /topological-sort/graph.ts: -------------------------------------------------------------------------------- 1 | export interface Node { 2 | name: string; 3 | neighbors: Node[]; 4 | } 5 | 6 | 7 | /* 8 | 9 | Sample graph to operate over. 10 | 11 | 1 12 | / \ 13 | 2 3 14 | / \ 15 | 0 4 16 | | | 17 | | 6 8-7 18 | \ / 19 | 5 20 | 21 | */ 22 | 23 | export const node0: Node = { 24 | name: '0', 25 | neighbors: [] 26 | }; 27 | 28 | export const node1: Node = { 29 | name: '1', 30 | neighbors: [] 31 | }; 32 | 33 | export const node2: Node = { 34 | name: '2', 35 | neighbors: [] 36 | }; 37 | 38 | export const node3: Node = { 39 | name: '3', 40 | neighbors: [] 41 | }; 42 | 43 | export const node4: Node = { 44 | name: '4', 45 | neighbors: [] 46 | }; 47 | 48 | export const node5: Node = { 49 | name: '5', 50 | neighbors: [] 51 | }; 52 | 53 | export const node6: Node = { 54 | name: '6', 55 | neighbors: [] 56 | }; 57 | 58 | export const node7: Node = { 59 | name: '7', 60 | neighbors: [] 61 | }; 62 | 63 | export const node8: Node = { 64 | name: '8', 65 | neighbors: [] 66 | }; 67 | 68 | node0.neighbors.push(node5); 69 | node1.neighbors.push(node3); 70 | node2.neighbors.push(); 71 | node3.neighbors.push(node0, node4); 72 | node4.neighbors.push(node6); 73 | node5.neighbors.push(); 74 | node6.neighbors.push(node5); 75 | 76 | node7.neighbors.push(); 77 | node8.neighbors.push(node7); 78 | -------------------------------------------------------------------------------- /topological-sort/topological-sort.ts: -------------------------------------------------------------------------------- 1 | import { Node, node0, node1, node2, node5, node6, node8, node7, node4, node3 } from './graph'; 2 | 3 | const topologicalSort = (graph: Node[]) => { 4 | const dfs = (node: Node) => { 5 | if (currentPathSet.has(node) && !resultSet.has(node)) { 6 | throw new Error('Cycle in the graph ' + Array.from(currentPath).map(e => e.name).join(', ')); 7 | } 8 | if (visited.has(node)) { 9 | return; 10 | } 11 | visited.add(node); 12 | currentPathSet.add(node); 13 | currentPath.push(node); 14 | node.neighbors.forEach(dfs); 15 | result.push(node); 16 | resultSet.add(node); 17 | }; 18 | 19 | // We keep the visited nodes here. 20 | // This data structure doesn't change between traversals. 21 | const visited = new Set(); 22 | 23 | // We keep the visited nodes for the current traversal. 24 | // Here we use both an array and a set so we can preserve 25 | // the order but at the same time have quick look-ups. 26 | let currentPathSet: Set; 27 | let currentPath: Node[]; 28 | 29 | // Here we keep the result of the algorithm. Notice 30 | // that we have resultSet and result of types respectively 31 | // array and set. We want to preserve the order of the 32 | // sorted elements, but at the same time, we want to 33 | // make sure we don't throw if we visit a node that 34 | // is already part of the result set. The set data structure 35 | // allows us fast look-ups. 36 | const result: Node[] = []; 37 | const resultSet = new Set(); 38 | 39 | // We iterate over all the nodes in the graph. 40 | // For each node we invoke the dfs algorithm. 41 | // We need to do this because we don't have the guarantee 42 | // that the graph is connected. 43 | for (const node of graph) { 44 | currentPathSet = new Set(); 45 | currentPath = []; 46 | dfs(node); 47 | } 48 | 49 | return result; 50 | }; 51 | 52 | const order = topologicalSort([node0, node1, node2, node3, node4, node5, node6, node7, node8]); 53 | console.log('A topological order is', order.map(v => v.name).join(', ')); 54 | -------------------------------------------------------------------------------- /topological-sort/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | // "outDir": "./", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tries/index.js: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | constructor() { 3 | this.children = {}; 4 | } 5 | } 6 | 7 | class Trie { 8 | constructor() { 9 | this.root = new TrieNode(); 10 | } 11 | 12 | insert(word) { 13 | let node = this.root; 14 | for (let i = 0; i < word.length; i += 1) { 15 | const c = node.children[word[i]] || new TrieNode(); 16 | node.children[word[i]] = c; 17 | node = c; 18 | } 19 | } 20 | 21 | hasPrefix(word) { 22 | let node = this.root; 23 | for (let i = 0; i < word.length; i += 1) { 24 | const c = node.children[word[i]]; 25 | if (!c) { 26 | return false; 27 | } 28 | node = c; 29 | } 30 | return true; 31 | } 32 | 33 | has(word) { 34 | let node = this.root; 35 | for (let i = 0; i < word.length; i += 1) { 36 | const c = node.children[word[i]]; 37 | if (!c) { 38 | return false; 39 | } 40 | node = c; 41 | } 42 | return Object.keys(node.children).length === 0; 43 | } 44 | } 45 | 46 | const t = new Trie(); 47 | t.insert('foobar'); 48 | 49 | console.log(t.hasPrefix('foo')); 50 | console.log(t.hasPrefix('foo2')); 51 | console.log(t.hasPrefix('foobar')); 52 | console.log(t.has('foobar')); 53 | console.log(t.has('foo')); 54 | --------------------------------------------------------------------------------