Implementing JavaScript Concepts from Scratch
Tags: javascript
Published: 2024-04-07 12:26:35

In this article, we explore the foundational building blocks of JavaScript by crafting several key components from the ground up. As we delve into these concepts, we will apply a range of techniques, from basic to sophisticated, making this exploration valuable for both newcomers to the JavaScript world and professionals.

## TOC
- [`memoize()`](#memoize)
- [`Array.map()`](#arraymap)
- [`Array.filter()`](#arrayfilter)
- [`Array.reduce()`](#arrayreduce)
- [`bind()`](#bind)
- [`call()`, `apply()`](#callapply)
- [`setInterval()`](#setinterval)
- [`cloneDeep()`](#clonedeep)
- [`debounce()`](#debounce)
- [`throttle()`](#throttle)
- [`Promise`](#promise)
- [`EventEmitter`] (#eventemitter)


<a name="memoize"></a>
## `memoize()` 

### Task Description

Re-create the `memoize` function (from "lodash") which optimizes performance by caching the results of function calls. This ensures repeated function calls with the same arguments are quicker by returning cached results instead of recalculating.

### Implementation 

```javascript
function customSerializer(entity, cache = new WeakSet()) {
  if (typeof entity !== 'object' || entity === null) {
    return `${typeof entity}:${entity}`;
  }
  if (cache.has(entity)) {
    return 'CircularReference';
  }
  cache.add(entity);

  let objKeys = Object.keys(entity).sort();
  let keyRepresentations = objKeys.map(key =>
    `${customSerializer(key, cache)}:${
      customSerializer(entity[key], cache)
    }`
  );

  if (Array.isArray(entity)) {
    return `Array:[${keyRepresentations.join(',')}]`;
  }

  return `Object:{${keyRepresentations.join(',')}}`;
}


function myMemoize(fn) {
  const cache = new Map();

  return function memoized(...args) {
    const keyRep = args.map(arg => 
      customSerializer(arg)
    ).join('-');
    const key = `${typeof this}:${this}-${keyRep}`;

    if (cache.has(key)) {
      return cache.get(key);
    } else {
      const result = fn.apply(this, args);
      cache.set(key, result);
      return result;
    }
  };
}
```


### Key Aspects of the Implementation

1. **Caching Mechanism:** It uses a `Map` object, `cache`, to store the results of function invocations. The `Map` object is chosen for its efficient key-value pairing and retrieval capabilities.

2. **Custom Serializer**: The `customSerializer` function converts the function arguments into a string representation that serves as a cache key. This serialization accounts for basic types, objects (including nested objects), arrays, and circular references. For objects and arrays, their keys are sorted to ensure consistent string representations regardless of property declaration order.

3. **Serializing `this`**: The value of `this` refers to the object that a function is a method of. In JavaScript, methods can behave differently based on the object they are called with, i.e., the context in which they are invoked. This is because `this` provides access to the context object's properties and methods, and its value can vary depending on how the function is called.

4. **Circular References**: The circular reference occurs when an object references itself directly or indirectly through its properties. This can happen in more complex data structures where, for example, object `A` contains a reference to object `B`, and object `B` in turn directly or indirectly references object `A`. It is crucial to handle circular references to avoid infinite loops.

5. **Automatic Garbage Collection with `WeakSet`**: A `WeakSet` holds "weak" references to its objects, meaning that the presence of an object in a `WeakSet` does not prevent the object from being garbage-collected if there are no other references to it. This behavior is particularly useful in contexts where temporary tracking of object presence is needed without prolonging their lifetime unnecessarily. Since the `customSerializer` function might only require to mark the visitation of objects during the serialization process without storing additional data, employing a `WeakSet` would prevent potential memory leaks by ensuring that objects are not kept alive solely by their presence in the set.

<a name="arraymap"></a>
## `Array.map()`

### Task Description

Re-create the `Array.map()` which takes a transformation function as an argument. This transformation function will be executed on each element of the array, taking three arguments: the current element, the index of the current element, and the array itself. 

### Key Aspects of the Implementation

1. **Memory Pre-allocation**: The `new Array(this.length)` is used to create a pre-sized array to optimize memory allocation and improve performance by avoiding dynamic resizing as elements are added.

### Implementation

```javascript
Array.prototype.myMap = function(fn) {
  const result = new Array(this.length);
  for (let i = 0; i < this.length; i++) {
    result[i] = fn(this[i], i, this);
  }
  return result;
}
```

<a name="arrayfilter"></a>
## `Array.filter()`

### Task Description
Re-create the `Array.filter()` which takes a predicate function as input, iterates over the elements of the array on which it is called, applying the predicate to each element. It returns a new array consisting only of those elements for which the predicate function returns `true`.

### Key Aspects of the Implementation

1. **Dynamic Memory Allocation**: It dynamically adds qualifying elements to the `filteredArray`, making the method more memory efficient in cases where few elements pass the predicate function.

### Implementation

```typescript
Array.prototype.myFilter = function(pred) {
  const filteredArray = [];
  for (let i = 0; i < this.length; i++) {
    if (pred(this[i], i, this)) {
      filteredArray.push(this[i]);
    }
  }
  return filteredArray;
}
```

<a name="arrayreduce"></a>
## `Array.reduce()`

### Task Description

Re-create the `Array.reduce()` which executes a `reducer` function on each element of the array, resulting in a single output value. The `reducer` function takes four arguments: accumulator, currentValue, currentIndex, and the whole array.

### Key Aspects of the Implementation

1. **`initialValue` value**: The `accumulator` and `startIndex` are initialized based on whether an `initialValue` is passed as an argument. If `initialValue` is provided (meaning the `arguments.length` is at least `2`), the `accumulator` is set to this `initialValue`, and the iteration starts 0th elements. Otherwise, if no `initialValue` is provided, the 0th element of the array itself is used as the `initialValue`.

### Implementation
```javascript
Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = arguments.length >= 2 
    ? initialValue 
    : this[0];
  let startIndex = arguments.length >= 2 ? 0 : 1;

  for (let i = startIndex; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
}
```

<a name="bind"></a>
## `bind()`

### Task Description

Re-create the `bind()` function which allows an object to be passed as the context in which the original function is called, along with pre-specified initial arguments (if any). It should also support the use of the `new` operator, enabling the creation of new instances while maintaining the correct prototype chain.

### Implementation

```javascript

Function.prototype.mybind = function(context, ...bindArgs) {
  const self = this;
  const boundFunction = function(...callArgs) {
    const isNewOperatorUsed = new.target !== undefined;
    const thisContext = isNewOperatorUsed ? this : context;
    return self.apply(thisContext, bindArgs.concat(callArgs));
  };

  if (self.prototype) {
    boundFunction.prototype = Object.create(self.prototype);
  }

  return boundFunction;
};
```

### Key Aspects of the Implementation

1. **Handling `new` Operator**: The statement `const isNewOperatorUsed = new.target !== undefined;` checks whether the `boundFunction` is being called as a constructor via the `new` operator. If the `new` operator is used, the `thisContext` is set to the newly created object (`this`) instead of the provided `context`, acknowledging that instantiation should use a fresh context rather than the one provided during binding. 

2. **Prototype Preservation**: To maintain the prototype chain of the original function, `mybind` conditionally sets the prototype of `boundFunction` to a new object that inherits from `self.prototype`. This step ensures that instances created from the `boundFunction` (when used as a constructor) correctly inherit properties from the original function's prototype. This mechanism preserves the intended inheritance hierarchy and maintains instanceof checks.

### Example of Using `bind()` with `new`

Let's consider a simple constructor function that creates objects representing cars:

```javascript
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
```

Imagine we frequently create `Car` objects that are of make 'Toyota'. To make this process more efficient, we can use `bind` to create a specialized constructor for Toyotas, pre-filling the `make` argument:
```javascript
// Creating a specialized Toyota constructor with 'Toyota'
// as the pre-set 'make'
const ToyotaConstructor = Car.bind(null, 'Toyota');

// Now, we can create Toyota car instances
// without specifying 'make'
const myCar = new ToyotaConstructor('Camry', 2020);

// Output: Car { make: 'Toyota', model: 'Camry', year: 2020 }
console.log(myCar);
```

<a name="callapply"></a>
##  `call()`, `apply()`

### Task Description
Re-create `call()` and `apply()`  functions which allow to call a function with a given this value and arguments provided individually.

### Implementation
```javascript
Function.prototype.myCall = function(context, ...args) {
  const fnSymbol = Symbol('fnSymbol');
  context[fnSymbol] = this;
  
  const result = context[fnSymbol](...args);
  
  delete context[fnSymbol];
  
  return result;
};

Function.prototype.myApply = function(context, args) {
  const fnSymbol = Symbol('fnSymbol');
  context[fnSymbol] = this;

  const result = context[fnSymbol](...args);

  delete context[fnSymbol];
  
  return result;
};
```

### Key Aspects of the Implementation

1. **Symbol Usage for Property Naming**: To prevent overriding potential existing properties on the context object or causing unexpected behavior due to name collisions, a unique `Symbol` is used as the property name. This ensures that our temporary property doesn't interfere with the context object's original properties.

2. **Cleanup After Execution**: After the function call is executed, the temporary property added to the context object is deleted. This cleanup step is crucial to avoid leaving a modified state on the context object.

<a name="setinterval"></a>
## `setInterval()`

### Task Description
Re-create the `setInterval` using `setTimeout`. The function should repeatedly call a provided callback function at specified intervals. It returns a function that, when called, stops the interval.

### Implementation
```javascript
function mySetInterval(callback, interval) {
  let timerId;

  const repeater = () => {
    callback();
    timerId = setTimeout(repeater, interval);
  };

  repeater();

  return () => {
    clearTimeout(timerId);
  };
}
```

### Key Aspects of the Implementation

1. **Cancellation Functionality**: The returned function from `mySetInterval` provides a simple and direct way to cancel the ongoing interval without needing to expose or manage timer IDs outside of the function's scope.


<a name="clonedeep"></a>
## `cloneDeep()`

### Task Description
Re-create the `cloneDeep` function (from "lodash") that performs a deep copy of a given input. This function should be able to clone complex data structures including objects, arrays, maps, sets, dates, and regular expressions, maintaining the structure and type integrity of each element.

### Implementation
```javascript
function myCloneDeep(entity, map = new WeakMap()) {
  if (entity === null || typeof entity !== 'object') {
    return entity;
  }

  if (map.has(entity)) {
    return map.get(entity);
  }

  let cloned;
  switch (true) {
    case Array.isArray(entity):
      cloned = [];
      map.set(entity, cloned);
      cloned = entity.map(item => myCloneDeep(item, map));
      break;
    case entity instanceof Date:
      cloned = new Date(entity.getTime());
      break;
    case entity instanceof Map:
      cloned = new Map(Array.from(entity.entries(),
        ([key, val]) => 
        [myCloneDeep(key, map), myCloneDeep(val, map)]));
      break;
    case entity instanceof Set:
      cloned = new Set(Array.from(entity.values(),
        val => myCloneDeep(val, map)));
      break;
    case entity instanceof RegExp:
      cloned = new RegExp(entity.source,
                          entity.flags);
      break;
    default:
      cloned = Object.create(
        Object.getPrototypeOf(entity));
      map.set(entity, cloned);
      for (let key in entity) {
        if (entity.hasOwnProperty(key)) {
          cloned[key] = myCloneDeep(entity[key], map);
        }
      }
  }

  return cloned;
}
```


### Key Aspects of the Implementation

1. **Circular Reference Handling**: Utilizes a `WeakMap` to keep track of already visited objects. If an object is encountered that has already been cloned, the previously cloned object is returned, effectively handling circular references and preventing stack overflow errors.

2. **Handling of Special Objects**: Differentiates between several object types (`Array`, `Date`, `Map`, `Sets`, `RegExp`) to ensure that each type is cloned appropriately preserving their specific characteristics. 

    - **`Array`**: Recursively clones each element, ensuring deep cloning.
    - **`Date`**: Copies the date using its numeric value (timestamp).
    - **Maps and Sets**: Constructs a new instance, recursively cloning each entry (for `Map`) or value (for `Set`).
    - **`RegExp`**: Clones by creating a new instance with the source and flags of the original.

3. **Cloning of Object Properties**: When the input is a plain object, it creates an object with the same prototype as the original and then recursively clones each own property, ensuring deep cloning while maintaining the prototype chain.

4. **Efficiency and Performance**: Utilizes `WeakMap` for memoization to efficiently handle complex and large structures with repeated references and circularities, ensuring optimal performance by avoiding redundant cloning.


<a name="debounce"></a>
## `debounce()`

### Task Description
Re-create the `debounce` function (from "lodash") which allows to limit the frequency at which a given callback function can fire. When invoked repeatedly within a short time frame, only the last call is executed after the specified delay.

```javascript
function myDebounce(func, delay) {
  let timerId;
  const debounced = function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };

  debounced.cancel = function() {
    clearTimeout(timerId);
    timerId = null;
  };

  debounced.flush = function() {
    clearTimeout(timerId);
    func.apply(this, arguments);
    timerId = null;
  };

  return debounced;
}
```

### Key Aspects of the Implementation

1. **Cancellation Capability**: Introducing a `.cancel` method enables external control to cancel any pending execution of the debounced function. This adds flexibility, allowing the debounced function to be canceled in response to specific events or conditions.

2. **Immediate Execution through Flush**: The `.flush` method allows for the immediate execution of the debounced function, disregarding the delay. This is useful in scenarios where it's necessary to ensure that the effects of the debounced function are applied immediately, for example, before unmounting a component or completing an interaction.

<a name="throttle"></a>
## `throttle()`

### Task Description
Re-create the `throttle` function (from "lodash") which ensures that a given callback function is only called at most once per specified interval (in the beginning in our case). Unlike debouncing, throttling guarantees a function execution at regular intervals, ensuring that updates are made, albeit at a controlled rate.


### Implementation
```javascript
function myThrottle(func, timeout) {
  let timerId = null;
  
  const throttled = function(...args) {
    if (timerId === null) {
      func.apply(this, args)
      timerId = setTimeout(() => {
        timerId = null;
      }, timeout)
    }
  }

  throttled.cancel = function() {
    clearTimeout(timerId);
    timerId = null;
  };
  
  return throttled;
}
```

### Key Aspects of the Implementation

1. **Cancellation Capability**: Introducing a `.cancel` method enables the ability to clear any scheduled reset of the throttle timer. This is useful in cleanup phases, such as component unmounting in UI libraries/frameworks, to prevent stale executions and to manage resources effectively.

<a name="promise"></a>
## `Promise`

### Task Description

Re-create the `Promise` class. It is a construct designed for asynchronous programming, allowing the execution of code to be paused until an async process is completed. At its core, a promise represents a proxy for a value not necessarily known at the time of its creation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. `Promise` includes methods to handle fulfilled and rejected states (`then`, `catch`), and to execute code regardless of the outcome (`finally`).

```javascript
class MyPromise {
  constructor(executor) {
    ...
  }

  then(onFulfilled, onRejected) {
    ...
  }

  catch(onRejected) {
    ...
  }

  finally(callback) {
    ...
  }
}
```

### `constructor` Implementation

```javascript
constructor(executor) {
  this.state = 'pending';
  this.value = undefined;
  this.reason = undefined;
  this.onFulfilledCallbacks = [];
  this.onRejectedCallbacks = [];

  const resolve = (value) => {
    if (this.state === 'pending') {
      this.state = 'fulfilled';
      this.value = value;
      this.onFulfilledCallbacks.forEach(fn => fn());
    }
  };

  const reject = (reason) => {
    if (this.state === 'pending') {
      this.state = 'rejected';
      this.reason = reason;
      this.onRejectedCallbacks.forEach(fn => fn());
    }
  };

  try {
    executor(resolve, reject);
  } catch (error) {
    reject(error);
  }
}
```

### Key Aspects of the `constructor` Implementation
1. **State Management**: Initializes with a state of 'pending'. Switches to 'fulfilled' when resolved, and 'rejected' when rejected.
2. **Value and Reason**: Holds the eventual result of the promise (`value`) or the reason for rejection (`reason`).
- **Handling Asynchrony**: Accepts an `executor` function that contains the asynchronous operation. The `executor` takes two functions, `resolve` and `reject`, which when called, transition the promise to the corresponding state.
3. **Callback Arrays**: Queues of callbacks (`onFulfilledCallbacks`, `onRejectedCallbacks`) are maintained for deferred actions pending the resolution or rejection of the promise.


### `.then` Implementation

```javascript
resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError(
      'Chaining cycle detected for promise'));
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}

then(onFulfilled, onRejected) {
  onFulfilled = typeof onFulfilled === 'function' ? 
    onFulfilled : value => value;
  
  onRejected = typeof onRejected === 'function' ? 
    onRejected : reason => { throw reason; };

  let promise2 = new MyPromise((resolve, reject) => {
    if (this.state === 'fulfilled') {
      setTimeout(() => {
        try {
          let x = onFulfilled(this.value);
          this.resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      });
    } else if (this.state === 'rejected') {
      setTimeout(() => {
        try {
          let x = onRejected(this.reason);
          this.resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      });
    } else if (this.state === 'pending') {
      this.onFulfilledCallbacks.push(() => {
        setTimeout(() => {
          try {
            let x = onFulfilled(this.value);
            this.resolvePromise(promise2, x, resolve,
              reject);
          } catch (error) {
            reject(error);
          }
        });
      });
      this.onRejectedCallbacks.push(() => {
        setTimeout(() => {
          try {
            let x = onRejected(this.reason);
            this.resolvePromise(promise2, x, resolve,
              reject);
          } catch (error) {
            reject(error);
          }
        });
      });
    }
  });

  return promise2;
}
```

### Key Aspects of the `.then` Implementation

1. **Default Handlers**: Converts non-function handlers to identity functions (for fulfillment) or throwers (for rejection) to ensure proper forwarding and error handling in promise chains.

2. **Promises Chaining**: The `then` method allows for the chaining of promises, enabling sequential asynchronous operations. It creates a new promise (`promise2`) that depends on the outcome of the callback functions (`onFulfilled`, `onRejected`) passed to it.

3. **Handling Resolution and Rejection**: The provided callbacks are only called once the current promise is settled (either fulfilled or rejected). The result (`x`) of each callback potentially being a value or another promise, dictates the resolution of `promise2`.
    
4. **Preventing Chaining Cycles**: The `resolvePromise` function checks if `promise2` is the same as the result (`x`), avoiding cycles where a promise waits on itself, resulting in a `TypeError`.

5. **Support for MyPromise and Non-Promise Values**: If the result (`x`) is an instance of `MyPromise`, `then` uses its resolution or rejection to settle `promise2`. This capability supports seamless integration of promise-based operations, both from instances of `MyPromise` and native JavaScript promises, assuming they share similar behavior. For non-promise values, or when `onFulfilled` or `onRejected` simply return a value, `promise2` is resolved with that value, enabling simple transformations or branching logic within promise chains.

6. **Asynchronous Execution Guarantees**: By deferring execution of `onFulfilled` and `onRejected` with `setTimeout`, `then` ensures asynchronous behavior. This delay maintains a consistent execution order, guaranteeing `onFulfilled` and `onRejected` are called after the execution stack is clear.

7. **Error Handling**: Should an exception occur within either `onFulfilled` or `onRejected`, `promise2` is rejected with the error, allowing error handling to propagate through the promise chain.

### `catch` and `finally` Implementation

```javascript
static resolve(value) {
  if (value instanceof MyPromise) {
    return value;
  }
  return new MyPromise((resolve, reject) => resolve(value));
}

catch(onRejected) {
  return this.then(null, onRejected);
}

finally(callback) {
  return this.then(
    value => MyPromise.resolve(callback())
              .then(() => value),
    reason => MyPromise.resolve(callback())
              .then(() => { throw reason; })
  );
}
```

### Key Aspects of the `.catch` Implementation:
1. **Simplified Error Handling:** The `.catch` method is a shorthand for `.then(null, onRejected)`, focusing exclusively on handling rejection scenarios. It allows for a cleaner syntax when only a rejection handler is needed, improving readability and maintainability of the code.
2. **Promise Chaining Support:** As it internally delegates to `.then`, `.catch` returns a new promise, maintaining the promise chaining capabilities. This allows for continued chain operations after error recovery or propagation of the error by rethrowing or returning a new rejected promise.
3. **Error Propagation:** If `onRejected` is provided and executes without errors, the returned promise is resolved with the return value of `onRejected`, effectively allowing for error recovery within a promise chain. If `onRejected` throws an error or returns a rejected promise, the error is propagated down the chain.

### Key Aspects of the `.finally` Implementation:
1. **Always Executes:** The `.finally` method ensures the provided `callback` is executed regardless of whether the promise is fulfilled or rejected. This is particularly useful for cleanup actions that need to occur after asynchronous operations, independent of their outcome.
2. **Return Value Preservation:** While the `callback` in `.finally` does not receive any argument (unlike in `.then` or `.catch`), the original fulfillment value or rejection reason of the promise is preserved and passed through the chain. The returned promise from `.finally` is resolved or rejected with the same value or reason, unless the `callback` itself results in a rejected promise.
3. **Error Handling and Propagation:** If the `callback` executes successfully, the promise returned by `.finally` is settled in the same manner as the original promise. However, if the `callback` throws an error or returns a rejected promise, the returned promise from `.finally` is rejected with this new error, allowing for error interception and alteration of the rejection reason in the promise chain.


<a name="eventemitter"></a>
## `EventEmitter`

### Task Description

Re-create the `EventEmitter` class which allows for the implementation of the Observer pattern, enabling objects (called "emitters") to emit named events that cause previously registered listeners (or "handlers") to be called. This is a key component in Node.js for handling asynchronous events and is widely used for signaling and managing application states and behaviors. Implementing a custom `EventEmitter` involves creating methods for registering event listeners, triggering events, and removing listeners.

```javascript
class MyEventEmitter {
  constructor() {
    this.events = {};
  }

  on(eventName, listener) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(listener);
  }

  once(eventName, listener) {
    const onceWrapper = (...args) => {
      listener.apply(this, args);
      this.off(eventName, onceWrapper);
    };
    this.on(eventName, onceWrapper);
  }

  emit(eventName, ...args) {
    const listeners = this.events[eventName];
    if (listeners && listeners.length) {
      listeners.forEach((listener) => {
        listener.apply(this, args);
      });
    }
  }

  off(eventName, listenerToRemove) {
    if (!this.events[eventName]) {
      return;
    }
    const filterListeners = 
      (listener) => listener !== listenerToRemove;
    this.events[eventName] = 
      this.events[eventName].filter(filterListeners);
  }
}
```

### Key Aspects of the `EventEmitter` Implementation

1. **EventListener Registration `.on`:** Adds a listener function to the array of listeners for a specified event, creating a new array if one does not already exist for that event name.

2. **One-time Event Listener `.once`:** Registers a listener that removes itself after being invoked once. It wraps the original listener in a function (`onceWrapper`) that will also remove the wrapper after execution, ensuring the listener only fires once.

3. **Emitting Events `.emit`:** Triggers an event, calling all registered listeners with the provided arguments. It applies the arguments to each listener function, allowing data to be passed to listeners.

4. **Removing Event Listeners `.off`:** Removes a specific listener from an event's listener array. If the event has no listeners after the removal, it could be left as an empty array or optionally cleaned up further (not shown in this implementation).