Skip to content

[1-team] 조이 과제 추가 #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 1-team
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/refactoring/areumsheep/answers/1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// 랜덤한 숫자 배열에서 짝수 위치는 더하고, 홀수 위치는 곱한 후에 순서대로 누적해라

const { pipe } = require('../utils/pipe');

const 짝수_더하기_홀수_곱하기 = (array) => {
return array.reduce((acc, cur, idx, arr) => {
if (idx % 2 === 0) acc.push(cur + (arr[idx - 2] ?? 0));
else acc.push(cur * (arr[idx - 2] ?? 1));
return acc;
}, []);
};

const 배수_분리하기 = (array) => {
const t = [];
const h = [];

array.map((value) => {
if (value % 2 === 0) {
t.push(value);
}
if (value % 3 === 0) {
h.push(value);
}
});
return {
t: t,
h: h,
};
};

const call = pipe(짝수_더하기_홀수_곱하기, 배수_분리하기);
console.log(call([1, 2, 3, 4, 5, 6, 7]));

16 changes: 16 additions & 0 deletions src/refactoring/areumsheep/answers/2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// 전, 후 사이 공백이 존재하는 어떤 문자열을 입력받을 때,
// 쉼표 기준으로 문자열을 자르고
// 전, 후에 존재하는 공백은 제거하고
// 모든 문자열을 비교하고 중복된 값을 제거하고
// 문자열의 길이 순서대로 반환해주세요.

const { pipe } = require('../utils/pipe');
const { reduce } = require('../utils/reduce');

const splitByComma = (str) => str.split(',');
const trimArray = (array) => reduce(array, (acc, value) => acc.concat(value.trim()), []);
const distinctArray = (array) => [...new Set(array)];
const compareLength = (array) => array.sort((a, b) => a.length - b.length);

const call = pipe(splitByComma, trimArray, distinctArray, compareLength);
console.log(call('asfasdfkl , sdf,asdf as , ddsf,asdfnkl, as, as'));
19 changes: 19 additions & 0 deletions src/refactoring/areumsheep/example-1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// 같은 형태의 함수가 반복되는 것으로 보여 field 라는 값을 받아 공통으로 작업하는 함수를 만들었습니다.

const setFieldByName = (cart, name, field, value) => {
const item = cart[name];
const newItem = objectSet(item, field, value);
const newCart = objectSet(cart, name, newItem);
return newCart;
}

const setPriceByName = (cart, name, price) => setFieldByName(cart, name, 'price', price)
const setShippingByName = (cart, name, ship) => setFieldByName(cart, name, 'shipping', ship);
const setQuantityByName = (cart, name, quant) => setFieldByName(cart, name, 'quantity', quant);
const setTaxByName = (cart, name, tax) => setFieldByName(cart, name, 'tax', tax);

function objectSet(object, key, value) {
var copy = Object.assign({}, object);
copy[key] = value;
return copy;
}
19 changes: 19 additions & 0 deletions src/refactoring/areumsheep/example-2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// for (var i = 0; i < items.length; i++) { } << 형태가 반복된다....??


const forEach = (items, logic) => {
for (let i = 0; i < items.length; i++) {
logic(items[i]);
}
}

forEach(foods, (food) => {
cook(food);
eat(food);
});

forEach(dishes, (dish) => {
wash(dish);
dry(dish);
putAway(dish);
});
21 changes: 21 additions & 0 deletions src/refactoring/areumsheep/example-3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// try-catch가 과연 여기에 있어야하나???
// error는 어떻게 핸들링하면 좋은가?

var user = {
id: '1',
};

const catchError = (logic) => {
try {
logic();
} catch (error) {
console.log(`🚫 에러가 발생했어요: ${error.message}`)
}
}

const getUserData = async ({ id }) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users?id=${id}`);
return response.json();
}

catchError(getUserData);
5 changes: 5 additions & 0 deletions src/refactoring/areumsheep/internal_utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const isIterable = (value) => typeof value[Symbol.iterator] === "function";

exports.I = {
isIterable
};
57 changes: 57 additions & 0 deletions src/refactoring/areumsheep/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const PROMISES_STATE = Object.freeze({
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected',
});

class MyPromise {
#state = PROMISES_STATE.pending;
#value;
#resolveLastcalls = [];
#rejectLastcalls = [];

constructor(fn) {
try {
fn(this.#resolve.bind(this), this.#reject.bind(this));
} catch (e) {
this.#reject(e);
}
}

#resolve(value) {
queueMicrotask(() => {
this.#state = PROMISES_STATE.fulfilled;
this.#value = value;
this.#resolveLastcalls.forEach(call => call(this.#state));
});
}
#reject(error) {
queueMicrotask(() => {
this.#state = PROMISES_STATE.rejected;
this.#value = error;
this.#rejectLastcalls.forEach(call => call(this.#state));
});
}

then(callback) {
if (this.#state === PROMISES_STATE.pending) {
return new MyPromise(resolve => {
this.#resolveLastcalls.push(() => resolve(callback(this.#value)));
});
} else if (this.#state === PROMISES_STATE.fulfilled) {
return new MyPromise(resolve => resolve(callback(this.#value)));
}
}
catch(callback) {
if (this.#state === PROMISES_STATE.rejected) {
callback(this.#value);
}
return this;
}
finally(callback) {
return this.then((value) => {
callback();
return value;
})
}
}
23 changes: 23 additions & 0 deletions src/refactoring/areumsheep/utils/generator_utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { timer, getMockData } = require('./lib');
const { L } = require('./lazy/_index');

const users = getMockData();

timer.start();
const job = L.pipe(
L.map(user => user.age),
L.filter(age => age > 50),
);
const test = job(users);
timer.end();

console.log(test.next());
console.log(test.next());
console.log(test.next());

timer.start();
users
.map(user => user.age)
.filter(age => age > 50)
.slice(2);
timer.end();
15 changes: 15 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/_index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { filter } = require('./filter');
const { groupBy } = require('./groupBy');
const { map } = require('./map');
const { pipe } = require('./pipe');
const { reduce } = require('./reduce');
const { uniqueBy } = require('./uniqueBy');

exports.L = {
filter,
groupBy,
map,
pipe,
reduce,
uniqueBy,
};
9 changes: 9 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/filter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function filter(fn) {
return function* (iter) {
for (const item of iter) {
if (fn(item)) yield item;
}
};
}

exports.filter = filter;
21 changes: 21 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/groupBy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { I } = require('../../internal_utils');
const { NL } = require('../non-lazy/_index');

const groupBy = (condition) => {
return (iter) => {
if (!I.isIterable(iter)) {
iter = Object.values(iter);
}
return NL.reduce(iter, (acc, value) => {
let key = value[condition];
if (typeof condition === 'function') {
key = condition(value);
}
acc[key] = acc[key] || [];
acc[key].push(value);
return acc;
}, {});
};
};

exports.groupBy = groupBy;
9 changes: 9 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function map(fn) {
return function* (iter) {
for (const item of iter) {
yield fn(item);
}
};
}

exports.map = map;
8 changes: 8 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/pipe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { NL } = require('../non-lazy/_index');

const pipe =
(...logics) =>
target =>
NL.reduce(logics, (value, logic) => logic(value), target);

exports.pipe = pipe;
22 changes: 22 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/reduce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
function reduce(fn) {
return (array, initialValue) => {
let i = -1;
let returnValue = initialValue;
const arrayLength = array.length;

if (initialValue === undefined && arrayLength >= 1) {
i++;
returnValue = array[0];
}
if (returnValue === undefined) {
throw new TypeError('Reduce of empty array with no initial value');
}

while (++i < arrayLength) {
returnValue = fn(returnValue, array[i], i, ...array);
}
return returnValue;
}
}

exports.reduce = reduce;
13 changes: 13 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/test/groupBy.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { L } = require('../_index');
const { NL } = require('../../non-lazy/_index');

describe('groupBy 테스트', () => {
describe('lazy', () => {
it('case: 1, Advanced', () => {
const decimalNumbers = [2.3, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 3.2, 2.6, 2.8];
const groupByFloor = L.groupBy(Math.floor);

expect(groupByFloor(decimalNumbers)).toEqual(NL.groupBy(decimalNumbers, Math.floor));
});
});
});
14 changes: 14 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/test/reduce.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { L } = require('../_index');
const { NL } = require('../../non-lazy/_index');

describe('reduce 테스트', () => {
describe('lazy', () => {
it('case: 1, Advanced', () => {
const decimalNumbers = [2.3, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 3.2, 2.6, 2.8];
const addSum = L.reduce((acc, value) => acc + value);

expect(addSum(decimalNumbers)).toEqual(NL.reduce(decimalNumbers, (acc, value) => acc + value));
});

});
});
13 changes: 13 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/test/uniqueBy.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { L } = require('../_index');
const { NL } = require('../../non-lazy/_index');

describe('uniqueBy 테스트', () => {
describe('lazy', () => {
it('case: 1, Advanced', () => {
const decimalNumbers = [2.3, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 3.2, 2.6, 2.8];
const uniqueByFloor = L.uniqueBy(Math.floor);

expect(uniqueByFloor(decimalNumbers)).toEqual(NL.uniqueBy(decimalNumbers, Math.floor));
});
});
});
35 changes: 35 additions & 0 deletions src/refactoring/areumsheep/utils/lazy/uniqueBy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { I } = require('../../internal_utils');
const { NL } = require('../non-lazy/_index');

const uniqueBy = callback => {
const map = new Map();
return iter => {
if (!I.isIterable(iter)) {
return [];
}
return NL.reduce(
iter,
(acc, item) => {
let key;
// Object인 경우
if (!Array.isArray(item)) {
key = JSON.stringify(item);
}
// callback이 있는 경우
if (typeof callback === 'function') {
key = callback(item);
}

if (!map.has(key)) {
acc.push(item);
}
map.set(key, item);

return acc;
},
[],
);
};
};

exports.uniqueBy = uniqueBy;
Loading