Skip to content

Instantly share code, notes, and snippets.

@Akira-Hayasaka
Last active October 9, 2020 07:10
Show Gist options
  • Save Akira-Hayasaka/6be5f8cc2c8700243643ee85b33400ab to your computer and use it in GitHub Desktop.
Save Akira-Hayasaka/6be5f8cc2c8700243643ee85b33400ab to your computer and use it in GitHub Desktop.
functional & declarative
let sum = 0;
let numbers = [2, 4, 6, 10, 16];
for (let i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] - 1;
if (numbers[i] % 3 === 0) {
sum += numbers[i];
}
}
console.log("0", sum);
numbers = [2, 4, 6, 10, 16];
let reduced = numbers.map((n) => n - 1);
let divisible = reduced.filter((n) => n % 3 === 0);
sum = divisible.reduce((acc, n) => acc + n, 0);
console.log("1:", sum);
sum = numbers
.map((n) => n - 1)
.filter((n) => n % 3 === 0)
.reduce((acc, n) => acc + n, 0);
console.log("2:", sum);
const subtractOne = (n) => n - 1;
const isDivisibleBy3 = (n) => n % 3 === 0;
const add = (acc, n) => acc + n;
sum = numbers.map(subtractOne).filter(isDivisibleBy3).reduce(add, 0);
console.log("3:", sum);
const users = [
{ name: "alice", id: 0 },
{ name: "bob", id: 2 },
];
// curried function
const byId = (id) => {
return (item) => {
return item.id === id;
};
};
// const byId = (id) => (item) => item.id === id; // one line
console.log(users.find(byId(2) /*** partially apply id to 2 ***/));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment