JavaScript hashMap constructor

Why hashMap’s constructor includes map functrion,

	constructor(size = 0) {
		this.hashmap = new Array(size).fill(null).map(() => new LinkedList());
	}

when it could just do the same with only fill:

	constructor(size = 0) {
		this.hashmap = new Array(size).fill(new LinkedList());
	}

Or am I missing something and it makes a diffrence?
JS hasmaps

I had this same thought when I first came across this exercise - it does make a difference. The code using only fill() is just creating one instance of LinkedList and filling the array with references to that same instance. The nature of the lesson can hide this because you’re implementing code to handle collisions in the HashMap, so it ends up finding another spot for the data anyway.

Consider the following:

class Random {
  constructor() {
    this.number = Math.floor(Math.random() * 10);
    console.log(`Constructor called - ${this.number}`);
  }
}

const arrayOne = new Array(5).fill(new Random());
console.table(arrayOne);
Constructor called - 1
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚ number β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚   1    β”‚
β”‚    1    β”‚   1    β”‚
β”‚    2    β”‚   1    β”‚
β”‚    3    β”‚   1    β”‚
β”‚    4    β”‚   1    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

// this changes them all because each element
// refers to the same instance of Random()
arrayOne[0].number = 50;
console.table(arrayOne);
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚ number β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚   50   β”‚
β”‚    1    β”‚   50   β”‚
β”‚    2    β”‚   50   β”‚
β”‚    3    β”‚   50   β”‚
β”‚    4    β”‚   50   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

const arrayTwo = new Array(5).fill(null).map(() => new Random());
console.table(arrayTwo);
Constructor called - 4
Constructor called - 9
Constructor called - 8
Constructor called - 4
Constructor called - 8
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚ number β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚   4    β”‚
β”‚    1    β”‚   9    β”‚
β”‚    2    β”‚   8    β”‚
β”‚    3    β”‚   4    β”‚
β”‚    4    β”‚   8    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜
3 Likes

Thanks a lot, i got it now! :wink: