Professional Documents
Culture Documents
3.1 Solid - Ocp.js
3.1 Solid - Ocp.js
freeze({
red: 'red',
green: 'green',
blue: 'blue'
});
class Product
{
constructor(name, color, size)
{
this.name = name;
this.color = color;
this.size = size;
}
}
class ProductFilter
{
filterByColor(products, color)
{
return products.filter(p => p.color === color);
}
filterBySize(products, size)
{
return products.filter(p => p.size === size);
}
// ↑↑↑ BEFORE
// ↓↓↓ AFTER
isSatisfied(item)
{
return item.color === this.color;
}
}
class SizeSpecification {
constructor(size)
{
this.size = size;
}
isSatisfied(item)
{
return item.size === this.size;
}
}
class BetterFilter
{
filter(items, spec)
{
return items.filter(x => spec.isSatisfied(x));
}
}
// specification combinator
class AndSpecification
{
constructor(...specs)
{
this.specs = specs;
}
isSatisfied(item)
{
return this.specs.every(x => x.isSatisfied(item));
}
}