Skip to content

Commit

Permalink
feat: hashing in JS
Browse files Browse the repository at this point in the history
  • Loading branch information
AE-Hertz committed Oct 30, 2024
1 parent 908059d commit 36ae88b
Show file tree
Hide file tree
Showing 6 changed files with 362 additions and 0 deletions.
52 changes: 52 additions & 0 deletions docs/Hashing/CollisionHandling.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,55 @@ print(hash_table.search('banana')) # Output: None

```

## Example: Chaining in JavaScript

```javascript
class HashTable {
constructor() {
this.table = Array.from({ length: 10 }, () => []); // Hash table with 10 slots
}

hash(key) {
let hash = 0;
for (let char of key.toString()) {
hash += char.charCodeAt(0);
}
return hash % this.table.length; // Simple hash function
}

insert(key, value) {
const index = this.hash(key);
for (let pair of this.table[index]) {
if (pair[0] === key) {
pair[1] = value; // Update if key exists
return;
}
}
this.table[index].push([key, value]); // Add new key-value pair
}

search(key) {
const index = this.hash(key);
for (let pair of this.table[index]) {
if (pair[0] === key) {
return pair[1]; // Return the value if key is found
}
}
return null; // Key not found
}

delete(key) {
const index = this.hash(key);
this.table[index] = this.table[index].filter(pair => pair[0] !== key); // Remove the key-value pair
}
}

// Example usage
const hashTable = new HashTable();
hashTable.insert('apple', 1);
hashTable.insert('banana', 2);
hashTable.insert('orange', 3);
console.log(hashTable.search('banana')); // Output: 2
hashTable.delete('banana');
console.log(hashTable.search('banana')); // Output: null
```
20 changes: 20 additions & 0 deletions docs/Hashing/OperationSearch.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,26 @@ hash_table = HashTable()
hash_table.table = {'apple': 10, 'banana': 20}
print(hash_table.search('apple')) # Output: 10
```
### Example Code (JavaScript)

```javascript
class HashTable {
constructor() {
this.table = {};
}

// Method to search for a key in the hash table
search(key) {
return this.table.hasOwnProperty(key) ? this.table[key] : null;
}
}

// Example usage
const hashTable = new HashTable();
hashTable.table = { apple: 10, banana: 20 };
console.log(hashTable.search('apple')); // Output: 10
```


### Conclusion

Expand Down
20 changes: 20 additions & 0 deletions docs/Hashing/OperationUpdate.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,26 @@ hash_table.table = {'apple': 10, 'banana': 20}
hash_table.update('apple', 30) # Updates value
```

### Example Code (Javascript)

```javascript
class HashTable {
constructor() {
this.table = {};
}

update(key, value) {
this.table[key] = value;
}
}

// Example usage
const hashTable = new HashTable();
hashTable.table = { 'apple': 10, 'banana': 20 };
hashTable.update('apple', 30); // Updates the value for 'apple'
console.log(hashTable.table); // Output: { 'apple': 30, 'banana': 20 }
```

### Conclusion

Update is critical for modifying data in hash tables, making them adaptable and suitable for dynamic applications.
47 changes: 47 additions & 0 deletions docs/Hashing/deletion-in-hash-table.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,53 @@ hash_table.table = {'apple': 10, 'banana': 20}
hash_table.delete('apple')
```

### Example Code (JavaScript)

```javascript
class HashTable {
constructor() {
this.table = new Map();
}

// Function to delete a key from the hash table
deleteKey(key) {
if (this.table.has(key)) {
this.table.delete(key); // Erase the key if it exists
console.log(`Key ${key} deleted.`);
} else {
console.log(`Key ${key} not found.`);
}
}

// Function to insert a key-value pair into the hash table
insert(key, value) {
this.table.set(key, value);
}

// Function to display the hash table
display() {
for (const [key, value] of this.table.entries()) {
console.log(`${key}: ${value}`);
}
}
}

// Example usage
const ht = new HashTable();

ht.insert(1, 100);
ht.insert(2, 200);
ht.insert(3, 300);

console.log("Hash Table before deletion:");
ht.display();

ht.deleteKey(2); // Deleting key 2

console.log("Hash Table after deletion:");
ht.display();
```

### Conclusion

Deletion is essential for maintaining the dynamic nature of a hash table by removing unwanted key-value pairs.
113 changes: 113 additions & 0 deletions docs/Hashing/hashsets.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,116 @@ int main() {
return 0;
}
```

### Example of HashSet Implementation in JavaScript


### 1. **HashSet Implementation**

```javascript
class HashSet {
constructor(size = 1000) {
this.size = size;
this.table = Array.from({ length: size }, () => []);
}

hashFunction(key) {
let hash = 0;
for (const char of key) {
hash += char.charCodeAt(0);
}
return hash % this.size;
}

add(key) {
const index = this.hashFunction(key);
if (!this.table[index].includes(key)) {
this.table[index].push(key);
}
}

contains(key) {
const index = this.hashFunction(key);
return this.table[index].includes(key);
}

remove(key) {
const index = this.hashFunction(key);
this.table[index] = this.table[index].filter(item => item !== key);
}
}

// Example usage
const hashSet = new HashSet();
hashSet.add("apple");
console.log("Contains 'apple':", hashSet.contains("apple")); // Output: true
hashSet.remove("apple");
console.log("Contains 'apple':", hashSet.contains("apple")); // Output: false
```

### 2. **Finding Duplicates in an Array**
Problem: Given an array, determine if it contains any duplicates.

```javascript
function containsDuplicates(nums) {
const hashSet = new Set();
for (const num of nums) {
if (hashSet.has(num)) {
return true; // Duplicate found
}
hashSet.add(num);
}
return false; // No duplicates found
}

// Example usage
console.log(containsDuplicates([1, 2, 3, 1])); // Output: true
console.log(containsDuplicates([1, 2, 3])); // Output: false
```

### 3. **Intersection of Two Arrays**
Problem: Given two arrays, return their intersection (common elements).

```javascript
function intersection(nums1, nums2) {
const set1 = new Set(nums1);
const result = [];
for (const num of nums2) {
if (set1.has(num)) {
result.push(num);
set1.delete(num); // Avoid duplicates in result
}
}
return result;
}

// Example usage
console.log(intersection([1, 2, 2, 1], [2, 2])); // Output: [2]
```

### 4. **Unique Email Addresses**
Problem: Given a list of email addresses, return the number of unique email addresses, ignoring periods . and any portion of the address after a plus sign + in the local name.

```javascript
function cleanEmail(email) {
const [local, domain] = email.split('@');
const cleanLocal = local.split('+')[0].replace(/\./g, '');
return `${cleanLocal}@${domain}`;
}

function uniqueEmails(emails) {
const uniqueSet = new Set();
for (const email of emails) {
uniqueSet.add(cleanEmail(email));
}
return uniqueSet.size;
}

// Example usage
const emails = [
"[email protected]",
"[email protected]",
"[email protected]"
];
console.log("Unique emails:", uniqueEmails(emails)); // Output: 2
```
Loading

0 comments on commit 36ae88b

Please sign in to comment.