Skip to content

Instantly share code, notes, and snippets.

@sanex3339
Created November 2, 2025 09:51
Show Gist options
  • Select an option

  • Save sanex3339/bc6973c6b9257243765f1e05306f02ea to your computer and use it in GitHub Desktop.

Select an option

Save sanex3339/bc6973c6b9257243765f1e05306f02ea to your computer and use it in GitHub Desktop.
// E-Commerce Shopping Cart Application
// Demonstrates comprehensive VM obfuscation with real-world patterns
// Product constructor function (OOP pattern without ES6 classes)
function Product(name, price, category, inStock) {
// Handle default parameter manually (ES5 compatible)
if (inStock === undefined) {
inStock = true;
}
this.name = name;
this.price = price;
this.category = category;
this.inStock = inStock;
this.id = Math.random().toString(36).substr(2, 9);
}
// Product methods attached to prototype
Product.prototype.getDisplayPrice = function() {
return `$${this.price.toFixed(2)}`;
};
Product.prototype.applyDiscount = function(percentage) {
const discount = this.price * (percentage / 100);
return this.price - discount;
};
Product.prototype.toString = function() {
return `${this.name} (${this.category}) - ${this.getDisplayPrice()}`;
};
// Shopping Cart with private state and closures
function createShoppingCart(taxRate) {
// Handle default parameter manually
if (taxRate === undefined) {
taxRate = 0.08;
}
// Private variables using closure
var items = [];
let discountPercentage = 0;
const maxItems = 50;
// Helper function for price calculation
const calculateItemTotal = function(item, quantity) {
// Handle default parameter manually
if (quantity === undefined) {
quantity = 1;
}
return item.price * quantity;
};
// Public API returned as object
return {
addItem: function(product, quantity) {
// Handle default parameter manually
if (quantity === undefined) {
quantity = 1;
}
if (items.length >= maxItems) {
throw new Error('Cart is full');
}
// Check if item already exists
const existingItem = items.find(item => item.product.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
items.push({ product, quantity });
}
return this;
},
removeItem: function(productId) {
const index = items.findIndex(item => item.product.id === productId);
if (index !== -1) {
items.splice(index, 1);
}
return this;
},
setDiscount: function(percentage) {
discountPercentage = Math.min(100, Math.max(0, percentage));
return this;
},
getSubtotal: function() {
return items.reduce((total, item) => {
return total + calculateItemTotal(item.product, item.quantity);
}, 0);
},
getDiscount: function() {
const subtotal = this.getSubtotal();
return subtotal * (discountPercentage / 100);
},
getTax: function() {
const afterDiscount = this.getSubtotal() - this.getDiscount();
return afterDiscount * taxRate;
},
getTotal: function() {
const subtotal = this.getSubtotal();
const discount = this.getDiscount();
const tax = this.getTax();
return subtotal - discount + tax;
},
getItemCount: function() {
return items.reduce((count, item) => count + item.quantity, 0);
},
getItems: function() {
return items.map(item => ({
name: item.product.name,
price: item.product.price,
quantity: item.quantity
}));
},
getMostExpensiveItem: function() {
if (items.length === 0) return null;
let maxPrice = 0;
let mostExpensive = null;
for (const item of items) {
const totalPrice = item.product.price * item.quantity;
if (totalPrice > maxPrice) {
maxPrice = totalPrice;
mostExpensive = item.product;
}
}
return mostExpensive ? mostExpensive.name : null;
},
getCategoryCounts: function() {
const counts = {};
items.forEach(item => {
const category = item.product.category;
counts[category] = (counts[category] || 0) + 1;
});
return counts;
},
hasCategory: function(category) {
return items.some(item => item.product.category === category);
},
getAveragePrice: function() {
if (items.length === 0) return 0;
const total = items.reduce((sum, item) => {
return sum + item.product.price * item.quantity;
}, 0);
const totalQuantity = items.reduce((sum, item) => sum + item.quantity, 0);
return total / totalQuantity;
},
generateReceipt: function() {
let receipt = 'RECEIPT\n';
// Add items
items.forEach(({ product, quantity }) => {
const itemTotal = product.price * quantity;
receipt += `${product.name}: $${itemTotal.toFixed(2)}\n`;
});
// Add totals
const subtotal = this.getSubtotal();
const discount = this.getDiscount();
const tax = this.getTax();
const total = this.getTotal();
receipt += `Subtotal: $${subtotal}\n`;
receipt += `Discount (${discountPercentage}%): -$${discount}\n`;
receipt += `Tax (${taxRate * 100}%): $${tax}\n`;
receipt += `Total: $${total}`;
return receipt;
},
// Clear all items
clear: function() {
items = [];
discountPercentage = 0;
return this;
}
};
}
// Main application execution
function runShoppingCartApp() {
// Create products
const products = [
new Product('Laptop', 1299.99, 'Electronics'),
new Product('Headphones', 199.99, 'Electronics'),
new Product('Desk Chair', 349.99, 'Furniture', false),
new Product('Keyboard', 89.99, 'Electronics'),
new Product('Mouse', 49.99, 'Electronics'),
new Product('Monitor', 599.99, 'Electronics'),
new Product('Webcam', 129.99, 'Electronics')
];
// Filter in-stock products
const availableProducts = products.filter(p => p.inStock);
// Create cart with 8% tax
const cart = createShoppingCart(0.08);
// Add items to cart using method chaining
cart
.addItem(availableProducts[0], 1) // Laptop
.addItem(availableProducts[1], 1) // Headphones
.addItem(availableProducts[2], 1) // Keyboard
.addItem(availableProducts[3], 1) // Mouse
.setDiscount(10);
// Update mouse quantity (test existing item update)
cart.addItem(availableProducts[3], 23);
// Calculate various metrics
const subtotal = cart.getSubtotal();
const itemCount = cart.getItemCount();
const discount = cart.getDiscount();
const tax = cart.getTax();
const total = cart.getTotal();
const mostExpensive = cart.getMostExpensiveItem();
const categoryCounts = cart.getCategoryCounts();
const hasElectronics = cart.hasCategory('Electronics');
const avgPrice = cart.getAveragePrice();
const receipt = cart.generateReceipt();
return {
cartTotal: subtotal,
itemCount: itemCount,
discountApplied: discount,
taxAmount: tax,
finalTotal: total,
mostExpensiveItem: mostExpensive,
categoryCount: Object.keys(categoryCounts).length,
hasElectronics: hasElectronics,
averagePrice: avgPrice,
formattedReceipt: receipt
};
}
// Execute and store result
var result = runShoppingCartApp();
console.log(result)
/*
{
cartTotal: 2789.73,
itemCount: 27,
discountApplied: 278.973,
taxAmount: 200.86056000000002,
finalTotal: 2711.61756,
mostExpensiveItem: 'Laptop',
categoryCount: 1,
hasElectronics: true,
averagePrice: 103.32333333333334,
formattedReceipt: 'RECEIPT\n' +
'Laptop: $1299.99\n' +
'Headphones: $199.99\n' +
'Keyboard: $89.99\n' +
'Mouse: $1199.76\n' +
'Subtotal: $2789.73\n' +
'Discount (10%): -$278.973\n' +
'Tax (8%): $200.86056000000002\n' +
'Total: $2711.61756'
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment