Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function each(array, f) {
- for (var i = 0; i < array.length; i++) {
- f(array[i]);
- }
- }
- function map(array, f) {
- var acc = [];
- each(array, function(element) {
- acc.push(f(element));
- });
- return acc;
- }
- function reduce(array, f, start) {
- var acc = start;
- each(array, function(element) {
- acc = f(acc, element);
- });
- return acc;
- }
- // function product(numbers) {
- // return reduce(numbers, function(acc, number) {
- // return acc * number;
- // }, 1);
- // }
- // console.log(product([1, 2, 3, 4]));
- // var people = [
- // {name: {first: "Alyssa", middle: "P.", last: "Hacker"}, age: 26},
- // {name: {first: "Ben", last: "Bitdiddle"}, age: 34},
- // {name: {first: "Eva", middle: "Lu", last: "Ator"}, age: 40},
- // {name: {first: "Lem", middle: "E.", last: "Tweakit"}, age: 45},
- // {name: {first: "Louis", last: "Reasoner"}, age: 21}
- // ];
- // function averageAge(people) {
- // var ages = map(people, function(person) {
- // return person.age;
- // });
- // console.log(ages);
- // return reduce(ages, function(acc, age) {
- // return acc += age;
- // }, 0) / ages.length;
- // }
- // console.log(averageAge(people));
- // function range(start, end) {
- // var acc = [];
- // for (var i = start; i < end; i++) {
- // acc.push(i);
- // }
- // return acc;
- // }
- // console.log(range(1, 5));
- // function factorial(n) {
- // return reduce(range(1, n + 1), function(acc, element) {
- // return acc *= element;
- // }, 1);
- // }
- // console.log(factorial(4));
- // var arr = [1, 2, 3]
- // function sumBy(numbers, f) {
- // return reduce(numbers, function(sum, number) {
- // return sum += f(number);
- // }, 0);
- // return sum;
- // }
- // function square(x) {
- // return x * x;
- // }
- // function cube(x) {
- // return x * x * x;
- // }
- //sumBy(arr, square); // => 30
- //Note: you will have to create a function "square" that returns the square of an input number.
- //sumBy(arr, cube); // => 100
- //Note: you will have to create a function "cube" that returns the cube of an input number.
- // function max(numbers) {
- // var max = numbers[0];
- // each(numbers, function(number) {
- // if (number > max) {
- // max = number;
- // }
- // });
- // return max;
- // }
- // function max(numbers) {
- // return reduce(numbers, function(max, number) {
- // console.log(number, max);
- // if(number > max) {
- // return max = number;
- // }
- // }, numbers[0]);
- // }
- // console.log(max([1, 2, 3, 4, 5]));
Add Comment
Please, Sign In to add comment