Skip to content

Instantly share code, notes, and snippets.

@loraxx753
Created February 19, 2025 22:56
Show Gist options
  • Save loraxx753/b300f1144c1f0d1428b4b6fb16e7539b to your computer and use it in GitHub Desktop.
Save loraxx753/b300f1144c1f0d1428b4b6fb16e7539b to your computer and use it in GitHub Desktop.

Quick Reference: OOP vs. Functional Programming in JavaScript

🚨 The Problem with Singletons in JavaScript

❌ Singleton Example (Creates Shared State)

class TempTool {
  constructor() {
    this.data = [];
  }

  add(item) {
    this.data.push(item);
  }

  listAll() {
    return this.data;
  }
}

export default { instance: new TempTool() };

πŸ”₯ Issues:

  • Shared state across imports β†’ One test modifying state affects all subsequent tests.
  • Difficult to reset state β†’ Requires manual instance resets.
  • Mocking is harder β†’ Singleton is instantiated before tests, making it difficult to override.

βœ… Solution: Use Pure Functions or Dependency Injection Instead


βœ… Functional Programming: Predictable & Testable Code

1. What is a Pure Function?

  • Same input β†’ Always same output
  • No side effects
  • Easier to test and debug

βœ… Example: A Pure Function

function add(a, b) {
  return a + b;
}

console.log(add(5, 4)); // 9
console.log(add(5, 4)); // 9
console.log(add(5, 4)); // 9

module.exports = { add };

πŸ§ͺ Testing a Pure Function

const { add } = require("./demo");

describe("Add function", () => {
  it("adds two inputs", () => {
    expect(add(4, 5)).toEqual(9);
  });
});

❌ Impure Functions: Why They Make Testing Harder

Example: An Impure Function

function add(a, b) {
  return a + b + Math.random();
}

⚠️ Testing Problem:

const { add } = require("./demo");

describe("Add function", () => {
  it("adds two inputs", () => {
    const output = add(4, 5);
    expect(output).toEqual(); // ❌ What is the expected output?
  });
});

πŸ›  Fixing Impure Functions Using Mocks

βœ… Stabilizing Tests by Mocking Randomness

const { add } = require("./demo");

describe("Add function", () => {
  it("adds two inputs", () => {
    jest.spyOn(Math, "random").mockImplementation(() => 10);

    const output = add(4, 5);
    expect(output).toEqual(19);
  });
});

πŸ† Key Takeaways

βœ” Avoid Singletons – They introduce shared state issues and make testing difficult.
βœ” Use Pure Functions – They make your code more predictable and testable.
βœ” Mock Impure Functions – When external dependencies exist, mock them to create repeatable results.

πŸ”— Further Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment