Skip to content

Commit

Permalink
feat: 🎸 add more reduce sample
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangtranson committed Aug 2, 2023
1 parent a0a7ffd commit f5afcde
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
27 changes: 26 additions & 1 deletion arrays/reducing.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,34 @@ function flattenArrayObjectMethod3(arr) {
return arr.reduce((obj, current) => ({...obj, [current.key]: current.value}), {});
}

function mapping(list, fn) {
return list.reduce( (newList, item) => newList.concat(fn(item)), []);
}

function findMin(arr) {
return arr.reduce((min, curr) => curr < min ? curr : min, arr[0]);
}

function findMax(arr) {
return arr.reduce((max, curr) => curr > max ? curr : max, arr[0]);
}

function findUniqueValues(arr) {
return arr.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
}

module.exports = {
sum,
flattenArrayObjectMethod1,
flattenArrayObjectMethod2,
flattenArrayObjectMethod3
flattenArrayObjectMethod3,
mapping,
findMin,
findMax,
findUniqueValues
};
41 changes: 40 additions & 1 deletion arrays/reducing.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
const { sum, flattenArrayObjectMethod1, flattenArrayObjectMethod2, flattenArrayObjectMethod3 } = require('./reducing');
const {
sum,
flattenArrayObjectMethod1,
flattenArrayObjectMethod2,
flattenArrayObjectMethod3,
mapping,
findMin,
findMax,
findUniqueValues
} = require('./reducing');

describe('sum', () => {
const arr = [1, 2, 3];
Expand Down Expand Up @@ -34,4 +43,34 @@ describe('flatten array of objects', () => {
it('flattenArrayObjectMethod3 should flatten an array of objects', () => {
expect(flattenArrayObjectMethod3(arr)).toEqual(expected);
});
});


describe('map using reduce', () => {
const arr = [1, 2, 3];
const fn = (x) => x * 2;

it('should map an array', () => {
expect(mapping(arr, fn)).toEqual([2, 4, 6]);
});
});

describe('find min and max using reduce', () => {
const arr = [1, 2, 3, 4, 5];

it('should find the min', () => {
expect(findMin(arr)).toEqual(1);
});

it('should find the max', () => {
expect(findMax(arr)).toEqual(5);
});
});

describe('find unique values using reduce', () => {
const arr = [1, 1, 2, 3, 3, 4, 5];

it('should find the unique values', () => {
expect(findUniqueValues(arr)).toEqual([1, 2, 3, 4, 5]);
});
});

0 comments on commit f5afcde

Please sign in to comment.