Skip to content

Instantly share code, notes, and snippets.

View ekrem-aktas's full-sized avatar

Ekrem ekrem-aktas

View GitHub Profile
const basket = [
{ name:"apple", type: "fruit", calories: 52 },
{ name:"broccoli", type: "vegetable", calories: 45 },
{ name:"banana", type: "fruit", calories: 89 }
];
// Try to understand acc without looking at the last line
const { avgCalories } = basket.reduce((acc, food) => {
if (food.type !== "fruit"){
return acc;
const basket = [
{ name:"apple", type: "fruit" },
{ name:"broccoli", type: "vegetable" }
];
// Array.reduce can be used to filter fruits
const fruits = basket.reduce((acc, food) => food.type === "fruit" ? acc.concat(food) : acc, []);
// But Array.filter is better for it
const fruits = basket.filter(food => food.type === "fruit");
const basket = [
{ name:"apple", type: "fruit" },
{ name:"broccoli", type: "vegetable" }
];
// Add prices to each food in the basket
const basketWithPrices = basket.reduce((acc, food) => acc.concat({ ...food, price: getPrice(food) }), []);
// But Array.map is better for it
const basketWithPrices = basket.map(food => ({ ...food, price: getPrice(food)}));
const numbers = [1, 2, 3];
const total = numbers.reduce((sum, num) => sum + num);
console.log(total); // 6
const numbers = [1, 2, 3];
let total = 0;
numbers.forEach(num => total += num);
console.log(total) // 6
const members = [["name", "apple"], ["type", "fruit"]];
const food = members.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, Object.create(null));
console.log(food); // { name: "apple", type: "fruit" }
const members = [["name", "apple"], ["type", "fruit"]];
const obj = Object.create(null);
members.forEach(([key, value]) => obj[key] = value);
console.log(obj); // { name: "apple", type: "fruit" }
function groupBy(arr, func){
return arr
.reduce((acc, item) => {
const key = func(item);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, Object.create(null));
function groupBy(arr, func){
let grouped = Object.create(null);
arr.forEach((item) => {
const key = func(item);
if (!grouped[key]) {
grouped[key] = [];
}
grouped[key].push(item);
});
async function validateUsername(username) {
const errorNode = document.getElementById("error-text");
// Check if username is a non-empty string
if (typeof username !== "string" || username.trim() === "") {
errorNode.innerText = "Username is required";
return false;
}
// Check if username format is valid