Skip to content

style: use const when possible #230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backtracking/all_combinations_of_size_k.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
* and repeat the same process for the next number.
*/
export function generateCombinations(n: number, k: number): number[][] {
let combinationsAcc: number[][] = [];
let currentCombination: number[] = [];
const combinationsAcc: number[][] = [];
const currentCombination: number[] = [];

function generateAllCombos(
n: number,
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/add_binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
export function addBinary(firstBinaryNo: string, secondBinaryNo: string): string {
let lengthOfFirstNumber: number = firstBinaryNo.length - 1;
let lengthOfSecondNumber: number = secondBinaryNo.length - 1;
let solution: string[] = [];
const solution: string[] = [];
let carry: number = 0;

while ( lengthOfFirstNumber >= 0 || lengthOfSecondNumber >= 0) {
Expand Down
8 changes: 4 additions & 4 deletions data_structures/heap/heap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export abstract class Heap<T> {
}

public extract(): T {
let maxElement = this.heap[0];
const maxElement = this.heap[0];
this.heap[0] = this.heap[this.size() - 1];
this.heap.pop();
this.sinkDown();
Expand Down Expand Up @@ -162,8 +162,8 @@ export class PriorityQueue<T> extends MinHeap<T> {
}

protected swap(a: number, b: number) {
let akey = this.keys_index(this.heap[a]);
let bkey = this.keys_index(this.heap[b]);
const akey = this.keys_index(this.heap[a]);
const bkey = this.keys_index(this.heap[b]);
[this.keys[akey], this.keys[bkey]] = [this.keys[bkey], this.keys[akey]];
super.swap(a, b);
}
Expand All @@ -188,7 +188,7 @@ export class PriorityQueue<T> extends MinHeap<T> {
this.insert(value);
return;
}
let key = this.keys[idx];
const key = this.keys[idx];
if (this.compare(this.heap[key], value)) {
// Do not do anything if the value in the heap already has a higher priority.
return;
Expand Down
6 changes: 3 additions & 3 deletions data_structures/heap/test/heap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe("MaxHeap", () => {

beforeEach(() => {
heap = new MaxHeap();
for (let element of elements) {
for (const element of elements) {
heap.insert(element);
}
});
Expand Down Expand Up @@ -61,7 +61,7 @@ describe("MinHeap", () => {

beforeEach(() => {
heap = new MinHeap();
for (let element of elements) {
for (const element of elements) {
heap.insert(element);
}
});
Expand Down Expand Up @@ -106,7 +106,7 @@ describe("MinHeap", () => {
});

it("should increase priority", () => {
let heap = new PriorityQueue((a: number) => { return a; }, elements.length);
const heap = new PriorityQueue((a: number) => { return a; }, elements.length);
elements.forEach((element: number) => {
heap.insert(element);
});
Expand Down
2 changes: 1 addition & 1 deletion data_structures/queue/linked_queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class LinkedQueue<T> implements Queue<T> {
}

this.size--;
let head = this.head; // We store the head in order not to lose track of it
const head = this.head; // We store the head in order not to lose track of it
this.head = this.head.next; // Update the the head to the next node
return head.value; // Return the value of the head
}
Expand Down
2 changes: 1 addition & 1 deletion data_structures/stack/test/linked_list_stack.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { LinkedListStack } from "../linked_list_stack";

describe("Linked List Stack", () => {
let stack: LinkedListStack<number> = new LinkedListStack<number>(4);
const stack: LinkedListStack<number> = new LinkedListStack<number>(4);

stack.push(1);
stack.push(2);
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/knapsack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const knapsack = (
const numberOfItems = weights.length;

// Declaring a data structure to store calculated states/values
let dp: number[][] = new Array(numberOfItems + 1);
const dp: number[][] = new Array(numberOfItems + 1);

for (let i = 0; i < dp.length; i++) {
// Placing an array at each index of dp to make it a 2d matrix
Expand Down
2 changes: 1 addition & 1 deletion graph/bellman_ford.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
export const bellmanFord = (graph: [number, number][][], start: number): number[] | undefined => {
// We save the shortest distance to each node in `distances`. If a node is
// unreachable from the start node, its distance is Infinity.
let distances = Array(graph.length).fill(Infinity);
const distances = Array(graph.length).fill(Infinity);
distances[start] = 0;

// On the i'th iteration, we compute all shortest paths that consists of i+1
Expand Down
6 changes: 3 additions & 3 deletions graph/dijkstra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ import { MinHeap, PriorityQueue } from '../data_structures/heap/heap';
export const dijkstra = (graph: [number, number][][], start: number): number[] => {
// We use a priority queue to make sure we always visit the closest node. The
// queue makes comparisons based on path weights.
let priorityQueue = new PriorityQueue((a: [number, number]) => { return a[0] }, graph.length, (a: [number, number], b: [number, number]) => { return a[1] < b[1] });
const priorityQueue = new PriorityQueue((a: [number, number]) => { return a[0] }, graph.length, (a: [number, number], b: [number, number]) => { return a[1] < b[1] });
priorityQueue.insert([start, 0]);
// We save the shortest distance to each node in `distances`. If a node is
// unreachable from the start node, its distance is Infinity.
let distances = Array(graph.length).fill(Infinity);
const distances = Array(graph.length).fill(Infinity);
distances[start] = 0;

while (priorityQueue.size() > 0) {
const [node, _] = priorityQueue.extract();
graph[node].forEach(([child, weight]) => {
let new_distance = distances[node] + weight;
const new_distance = distances[node] + weight;
if (new_distance < distances[child]) {
// Found a new shortest path to child node. Record its distance and add child to the queue.
// If the child already exists in the queue, the priority will be updated. This will make sure the queue will be at most size V (number of vertices).
Expand Down
4 changes: 2 additions & 2 deletions graph/floyd_warshall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
*/
export const floydWarshall = (graph: number[][]): number[][] => {
let distances = structuredClone(graph);
let N = graph.length;
const N = graph.length;

// We begin by setting the weighted adjacency matrix as the shortest paths.
// For the k'th iteration, we try to relax the shortest paths by including node k in the path.
for (let k = 0; k < N; ++k) {
let newDistances = [];
const newDistances = [];
for (let i = 0; i < N; ++i) {
newDistances.push(Array(N).fill(Infinity));
}
Expand Down
14 changes: 7 additions & 7 deletions graph/johnson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,36 @@ import { dijkstra } from './dijkstra'
* @see https://en.wikipedia.org/wiki/Johnson%27s_algorithm
*/
export const johnson = (graph: [number, number][][]): number[][] | undefined => {
let N = graph.length;
const N = graph.length;

// Add a new node and 0 weighted edges from the new node to all existing nodes.
let newNodeGraph = structuredClone(graph);
let newNode: [number, number][] = [];
const newNodeGraph = structuredClone(graph);
const newNode: [number, number][] = [];
for (let i = 0; i < N; ++i) {
newNode.push([i, 0]);
}
newNodeGraph.push(newNode);

// Compute distances from the new node to existing nodes using the Bellman-Ford algorithm.
let adjustedGraph = bellmanFord(newNodeGraph, N);
const adjustedGraph = bellmanFord(newNodeGraph, N);
if (adjustedGraph === undefined) {
// Found a negative weight cycle.
return undefined;
}

for (let i = 0; i < N; ++i) {
for (let edge of graph[i]) {
for (const edge of graph[i]) {
// Adjust edge weights using the Bellman Ford output weights. This ensure that:
// 1. Each weight is non-negative. This is required for the Dijkstra algorithm.
// 2. The shortest path from node i to node j consists of the same nodes with or without adjustment.
edge[1] += adjustedGraph[i] - adjustedGraph[edge[0]];
}
}

let shortestPaths: number[][] = [];
const shortestPaths: number[][] = [];
for (let i = 0; i < N; ++i) {
// Compute Dijkstra weights for each node and re-adjust weights to their original values.
let dijkstraShorestPaths = dijkstra(graph, i);
const dijkstraShorestPaths = dijkstra(graph, i);
for (let j = 0; j < N; ++j) {
dijkstraShorestPaths[j] += adjustedGraph[j] - adjustedGraph[i];
}
Expand Down
10 changes: 5 additions & 5 deletions graph/kosajaru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const getNodePriorities = (graph: number[][], visited: boolean[], stack: number[

// Return the transpose of graph. The tranpose of a directed graph is a graph where each of the edges are flipped.
const transpose = (graph: number[][]): number[][] => {
let transposedGraph = Array(graph.length);
const transposedGraph = Array(graph.length);
for (let i = 0; i < graph.length; ++i) {
transposedGraph[i] = [];
}
Expand Down Expand Up @@ -52,20 +52,20 @@ const gatherScc = (graph: number[][], visited: boolean[], node: number, scc: num
* @see https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm
*/
export const kosajaru = (graph: number[][]): number[][] => {
let visited = Array(graph.length).fill(false);
const visited = Array(graph.length).fill(false);

let stack: number[] = [];
const stack: number[] = [];
for (let i = 0; i < graph.length; ++i) {
getNodePriorities(graph, visited, stack, i);
}

const transposedGraph = transpose(graph);

let sccs = [];
const sccs = [];
visited.fill(false);
for (let i = stack.length - 1; i >= 0; --i) {
if (!visited[stack[i]]) {
let scc: number[] = [];
const scc: number[] = [];
gatherScc(transposedGraph, visited, stack[i], scc);
sccs.push(scc);
}
Expand Down
6 changes: 3 additions & 3 deletions graph/kruskal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ import { DisjointSet } from '../data_structures/disjoint_set/disjoint_set';
*/
export const kruskal = (edges: Edge[], num_vertices: number): [Edge[], number] => {
let cost = 0;
let minimum_spanning_tree = [];
const minimum_spanning_tree = [];

// Use a disjoint set to quickly join sets and find if vertices live in different sets
let sets = new DisjointSet(num_vertices);
const sets = new DisjointSet(num_vertices);

// Sort the edges in ascending order by weight so that we can greedily add cheaper edges to the tree
edges.sort((a, b) => a.weight - b.weight);

for (let edge of edges) {
for (const edge of edges) {
if (sets.find(edge.a) !== sets.find(edge.b)) {
// Node A and B live in different sets. Add edge(a, b) to the tree and join the nodes' sets together.
minimum_spanning_tree.push(edge);
Expand Down
10 changes: 5 additions & 5 deletions graph/prim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ export const prim = (graph: [number, number][][]): [Edge[], number] => {
if (graph.length == 0) {
return [[], 0];
}
let minimum_spanning_tree: Edge[] = [];
const minimum_spanning_tree: Edge[] = [];
let total_weight = 0;

let priorityQueue = new PriorityQueue((e: Edge) => { return e.b }, graph.length, (a: Edge, b: Edge) => { return a.weight < b.weight });
let visited = new Set<number>();
const priorityQueue = new PriorityQueue((e: Edge) => { return e.b }, graph.length, (a: Edge, b: Edge) => { return a.weight < b.weight });
const visited = new Set<number>();

// Start from the 0'th node. For fully connected graphs, we can start from any node and still produce the MST.
visited.add(0);
add_children(graph, priorityQueue, 0);

while (!priorityQueue.isEmpty()) {
// We have already visited vertex `edge.a`. If we have not visited `edge.b` yet, we add its outgoing edges to the PriorityQueue.
let edge = priorityQueue.extract();
const edge = priorityQueue.extract();
if (visited.has(edge.b)) {
continue;
}
Expand All @@ -40,7 +40,7 @@ export const prim = (graph: [number, number][][]): [Edge[], number] => {

const add_children = (graph: [number, number][][], priorityQueue: PriorityQueue<Edge>, node: number) => {
for (let i = 0; i < graph[node].length; ++i) {
let out_edge = graph[node][i];
const out_edge = graph[node][i];
// By increasing the priority, we ensure we only add each vertex to the queue one time, and the queue will be at most size V.
priorityQueue.increasePriority(out_edge[0], new Edge(node, out_edge[0], out_edge[1]));
}
Expand Down
12 changes: 6 additions & 6 deletions graph/tarjan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ export const tarjan = (graph: number[][]): number[][] => {

let index = 0;
// The order in which we discover nodes
let discovery: number[] = Array(graph.length);
const discovery: number[] = Array(graph.length);
// For each node, holds the furthest ancestor it can reach
let low: number[] = Array(graph.length).fill(undefined);
const low: number[] = Array(graph.length).fill(undefined);
// Holds the nodes we have visited in a DFS traversal and are considering to group into a SCC
let stack: number[] = [];
const stack: number[] = [];
// Holds the elements in the stack.
let stackContains = Array(graph.length).fill(false);
let sccs: number[][] = [];
const stackContains = Array(graph.length).fill(false);
const sccs: number[][] = [];

const dfs = (node: number) => {
discovery[node] = index;
Expand All @@ -46,7 +46,7 @@ export const tarjan = (graph: number[][]): number[][] => {

if (discovery[node] == low[node]) {
// node is the root of a SCC. Gather the SCC's nodes from the stack.
let scc: number[] = [];
const scc: number[] = [];
let i;
for (i = stack.length - 1; stack[i] != node; --i) {
scc.push(stack[i]);
Expand Down
12 changes: 6 additions & 6 deletions graph/test/bellman_ford.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { bellmanFord } from "../bellman_ford";

const init_graph = (N: number): [number, number][][] => {
let graph = Array(N);
const graph = Array(N);
for (let i = 0; i < N; ++i) {
graph[i] = [];
}
Expand All @@ -16,7 +16,7 @@ describe("bellmanFord", () => {
}

it("should return the correct value", () => {
let graph = init_graph(9);
const graph = init_graph(9);
add_edge(graph, 0, 1, 4);
add_edge(graph, 0, 7, 8);
add_edge(graph, 1, 2, 8);
Expand All @@ -38,7 +38,7 @@ describe("bellmanFord", () => {
expect(bellmanFord([[]], 0)).toStrictEqual([0]);
});

let linear_graph = init_graph(4);
const linear_graph = init_graph(4);
add_edge(linear_graph, 0, 1, 1);
add_edge(linear_graph, 1, 2, 2);
add_edge(linear_graph, 2, 3, 3);
Expand All @@ -49,7 +49,7 @@ describe("bellmanFord", () => {
}
);

let unreachable_graph = init_graph(3);
const unreachable_graph = init_graph(3);
add_edge(unreachable_graph, 0, 1, 1);
test.each([[0, [0, 1, Infinity]], [1, [1, 0, Infinity]], [2, [Infinity, Infinity, 0]]])(
"correct result for graph with unreachable nodes with source node %i",
Expand All @@ -61,15 +61,15 @@ describe("bellmanFord", () => {

describe("bellmanFord negative cycle graphs", () => {
it("should returned undefined for 2-node graph with negative cycle", () => {
let basic = init_graph(2);
const basic = init_graph(2);
basic[0].push([1, 2]);
basic[1].push([0, -3]);
expect(bellmanFord(basic, 0)).toStrictEqual(undefined);
expect(bellmanFord(basic, 1)).toStrictEqual(undefined);
});

it("should returned undefined for graph with negative cycle", () => {
let negative = init_graph(5);
const negative = init_graph(5);
negative[0].push([1, 6]);
negative[0].push([3, 7]);
negative[1].push([2, 5]);
Expand Down
8 changes: 4 additions & 4 deletions graph/test/dijkstra.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { dijkstra } from "../dijkstra";
describe("dijkstra", () => {

const init_graph = (N: number): [number, number][][] => {
let graph = Array(N);
const graph = Array(N);
for (let i = 0; i < N; ++i) {
graph[i] = [];
}
Expand All @@ -16,7 +16,7 @@ describe("dijkstra", () => {
}

it("should return the correct value", () => {
let graph = init_graph(9);
const graph = init_graph(9);
add_edge(graph, 0, 1, 4);
add_edge(graph, 0, 7, 8);
add_edge(graph, 1, 2, 8);
Expand All @@ -38,7 +38,7 @@ describe("dijkstra", () => {
expect(dijkstra([[]], 0)).toStrictEqual([0]);
});

let linear_graph = init_graph(4);
const linear_graph = init_graph(4);
add_edge(linear_graph, 0, 1, 1);
add_edge(linear_graph, 1, 2, 2);
add_edge(linear_graph, 2, 3, 3);
Expand All @@ -49,7 +49,7 @@ describe("dijkstra", () => {
}
);

let unreachable_graph = init_graph(3);
const unreachable_graph = init_graph(3);
add_edge(unreachable_graph, 0, 1, 1);
test.each([[0, [0, 1, Infinity]], [1, [1, 0, Infinity]], [2, [Infinity, Infinity, 0]]])(
"correct result for graph with unreachable nodes with source node %i",
Expand Down
Loading