Solution: Compress Files with Switchable Encoders
Explore how to apply the Strategy Pattern in Node.js by creating a file compression utility that dynamically switches between Gzip, Brotli, and no compression strategies at runtime. Understand asynchronous compress methods and composition to avoid conditional logic.
We'll cover the following...
Solution explanation
Lines 2–22: We define three encoder strategies:
GzipEncoder,BrotliEncoder, andNoCompression.Each implements an asynchronous
.compress()method that returns aPromise.GzipEncodersimulates fast compression with a short delay.BrotliEncodertakes longer, reflecting higher compression cost.NoCompressionresolves immediately, returning the data unchanged.This demonstrates asynchronous strategies that share the same interface.
Lines 25–38: The
Compressorclass is the context.It stores a reference to the current encoder strategy. ...