ecmascript

Factory Functions in 2026: The Gulpfile Real-World Example

2026-02-02 ecmascript 2 min read

The Anatomy of a Factory

In 2026, the shift toward functional programming is total. At the heart of this is the Factory Function: a function that returns an object without the baggage of new or this. It's clean, it's private, and it's predictable.

Real World: The Gulp Task Factory

Designers often have multiple asset pipelines (CSS, JS, Images). Instead of writing three separate Gulp tasks that look almost identical, we use a Task Factory to generate them. This keeps our gulpfile.js maintainable and scalable.

javascript
// A Factory that creates a CSS compilation pipeline
function createStyleTask(options) {
  const { src, dest, isProduction } = options;

  return function compileStyles() {
    return gulp.src(src)
      .pipe(sass())
      .pipe(isProduction ? cleanCSS() : gulp.noop())
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest(dest));
  };
}

// Usage: Assembling our build horizontally
export const themeStyles = createStyleTask({ src: 'src/theme/*.scss', dest: 'dist/theme' });
export const adminStyles = createStyleTask({ src: 'src/admin/*.scss', dest: 'dist/admin' });

Horizontal Composition

As seen in the diagram below, we aren't building a vertical 'ladder' of classes. We are plugging logic modules directly into a new object instance.

Rendering diagram...

1. Prototype Chain vs. 2. Factory Composition

Traditional inheritance forces you to inherit everything from the 'parent.' Composition allows you to pick only the behaviors you need.

text
Vertical (Old): User -> Employee -> Manager -> Admin (Deep & Fragile)
Horizontal (New): User + { canEdit } + { canDelete } (Flat & Flexible)

Functional Delegation & Extension

We can 'decorate' an existing object by passing it through another factory. This is how we add specialized features without touching the original source code.

javascript
function withAuditLog(target) {
  return {
    ...target,
    logAction: (action) => console.log(`[LOG]: ${target.name} performed ${action}`)
  };
}

const proUser = withAuditLog(createUser('Kensley'));

Svelte 5 Integration

In Svelte 5, factories pair perfectly with the $state rune. This allows you to create reactive 'Stores' that are plain JavaScript objects, making them easy to test and reuse across projects.

javascript
export function createCounter(initial = 0) {
  let count = $state(initial);
  return {
    get value() { return count; },
    increment: () => count++
  };
}

Conclusion

Whether you are automating a Gulp build or managing Svelte state, factories offer a level of clarity that classes can't match. They prioritize privacy and composition, which are the hallmarks of a senior-level codebase in 2026.


You're reading the first article in this series.
End of this category