redis를 사용할 일이 생겨, redis npm 페이지를 들어갔더니 

npm-redis가 4.x 버전대로 업데이트가 되어있었다 

 

이번 업데이트하면서 뭔가 보여주고 싶은게 있나보다 싶었다

마이그레이션 가이드까지 내놧다 

업데이트가 되면서 @types/redis설치가 필요 없어졌고, 

기존에 하던 방식대로 Expire 시간을 정하면 에러가 발생한다

 

> Redis Expire option 관련된 공식문서이다 

https://redis.io/commands/expire/

 

EXPIRE

Set a key's time to live in seconds

redis.io

 

Redis 사용법

설치

npm install --save redis

 

적용 

import { createClient } from 'redis';
// redis[s]://[[username][:password]@][host][:port][/db-number]:

const redisTest = async () => {
  const connectURL = 'RedisURL'; // redis://root:1234@localhost:6380
  const client = createClient({
    url: connectURL,
  });
  await client.connect();

  const email = 'sol35352000@gmail.com';
  const code = 'A123ABFQIFP';

  await client.set(email, code, { EX: 10 });

  const data = await client.get(email);

  await client.quit();
};

 

원래 예전에 사용했던 Redis에서는 옵션에 포함되어 있지않고 밖에 나와있었다.

client.set(email, code, 10);

 

처음에는 옵션들을 보고 왜 expire가 없지 생각하면서 보다보니 EX가 있어서 

아.. 이거구나 싶었다 

 

어쩌피 변수명지을거면 풀네임으로 해줬음 좋겠다는 생각이... 불편...

반응형
dotenv를 사용할 일이 있어 서버에서와 같은 방식으로 dotenv를 설치하고 
사용하려는데 에러발생 
ERROR in ./node_modules/dotenv/lib/main.js 1:11-24

Module not found: Error: Can't resolve 'fs' in '/Users/user/Documents/projects/react/goback/node_modules/dotenv/lib'


ERROR in ./node_modules/dotenv/lib/main.js 3:13-28

Module not found: Error: Can't resolve 'path' in '/Users/user/Documents/projects/react/goback/node_modules/dotenv/lib' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }' - install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "path": false }

REACT_APP을 붙여야한다는 글을 보고 따라해봤는데도 그대로 였다 

REACT_APP을 안붙인게 이유였다면 dotenv를 불러오는데 에러가 나지는 않지... 

 

이유는 간단했다 

create-react-app으로 프로젝트를 생성하면 dotenv가 내장되어 있기 때문에 에러가 발생했던 것이었고

import했던 dotenv를 지우 package를 삭제하니 정상적으로 불러와진다 

반응형

'Front' 카테고리의 다른 글

[React] npm eject 되돌리기  (0) 2022.04.09

게시판 기능이 필요해서 만들던 중 

toast-ui와 ckeditor 둘 중 어떤걸로 할까 고민했다 

 

toast-ui를 적용하고 ckeditor도 적용해봤지만 후자가 조금 더 끌렸다 

원본을 사용하고 싶은 느낌... 

 

찾아보니 toast-ui dependency에 ckeditor가 존재하는 걸로 보아 ckeditor를 기반으로 라이브러리를 만든 듯 하다 

그래서 CKEditor를 적용하려 하는데 문제가 있었다 

 

뭔가.. 업데이트는 꾸준히 올라오지만 완성되지 않은 날것의 느낌? 

그래서 eject를 적용했고, webpack 파일을 수정하여 게시판을 만드는데 까지는 됬다 

하지만 고작 게시판하나 때문에 eject를 해야하나? 라는 생각이 들었고 

되돌리기 시작했다...

 

왜 eject 되돌리려하는가? 

우선은 CRA를 하게되면 스크립트를 제공하는데

이 스크립트로 인해 core한 부분은 신경쓰지 않아도 된다 

 

물론 고도화가 필요하다면 eject를 진행해야 하겠지만, 개발 초기단계부터 이런 리스크를 안고가고 싶지 않았다 

 

eject되돌리기 - 간단

1. eject를 하면서 생긴 디렉토리 정리 

2. node_modules 삭제 

3. package.json에 추가된 dependency 정리

4. react-script 설치 

5. package.json에 스크립트 추가 

 

eject되돌리기 

 

1.

우선 eject를 하면서 생긴 두개의 디렉토리 삭제 

src
  ㄴ scripts/
  ㄴ config/

 

2 ~ 3.

eject를 진행한 뒤 node_modules를 보면 CRA를 했을때는 보지못했던 babel관련 패키지들이 굉장히 많이 설치되어있다 

package.json > dependency에 새롭게 추가된 패키지들을 지우고, node_module도 지워준다 

 

4.

package 재설치

react-scripts패키지 설치 

npm i
npm i react-scripts

 

5.

package.json에 스크립트를 다시 추가해준다 

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

 

이렇게 하면 되돌려진다

 

하지만 가장 좋은 방법은 역시 새로운 브랜치에서 작업하기 

 

늘 새로운걸 적용하거나 추가한다면 기존의 develop, main 브랜치가 아닌

feature 브랜치를 따서 적용하도록 하자 

 

반응형

'Front' 카테고리의 다른 글

[React] dotenv에러  (0) 2022.04.12

You are given an array of unique integers salary where salary[i] is the salary of the ith employee.

Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500

Example 2:

Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000

 

난이도: easy

 

사원들 연봉의 평균을 구하는 문제이다

가장 높은 연봉을 받는 사원과 가장 낮은 연봉을 받는 사원을 제외한 나머지의 평균을 구해라 

 

var average = function(salary) {
    let result = 0;
    const sorted = salary.sort((a, b) => a - b);
    
    sorted.reduce((acc, cur) => {
        result += cur;
    })
    
    result = result - sorted[sorted.length - 1]
    
    return result / (salary.length - 2) 
};

 

1. 정렬

2. 연봉 합치기 (여기서 인덱스를 빈칸으로 두어 가장 낮은 연봉은 제외하고 더해준다) 

3. 가장 많은 연봉을 제외

4. 평균 구하기 

 

반응형

Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

 

Example 1:

Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].

난이도: easy

 

이 문제는 홀수인 숫자를 찾는 것으로

무조건 O(1)로 풀어야 된다라고 생각이 든게 그냥 들었다 

 

반복문으로 풀면 나눠서 count++ 해주면 되는데 이러면 분명 효율이 맨끝으로 갔을 것 같다 

 

var countOdds = function(low, high) {
    let count = 0;
    
    if (low % 2 === 1 || high % 2 === 1) count++
    
    count = count + Math.floor((high - low) / 2);

    return count;
};

 

문제에서 생각해줘야 할 부분은 

1. low: 홀수, high: 홀수

2. low, high 둘 중 하나 홀수

3. low: 짝수, high: 짝수

 

이렇게만 생각해주면 된다

Math.floor를 해줘서 둘 중 하나가 홀수인 경우를 해결해준다고 생각하면 된다 

 

풀이할 때 공책에 하나씩 적어가면서 규칙이 어떤지 찾아봤다

암산으로는 도저히 안풀려서 ㅋㅋㅋ 

 

반응형

The Tribonacci sequence Tn is defined as follows:

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

 

Example 1:

Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

Example 2:

Input: n = 25
Output: 1389537

 

이 문제는 피보나치를 이해하고 풀이를 했는가를 물어보기 위해 나온 문제인듯 하다 

원래 하던 피보나치 풀이에 숫자를 하나 더 더해주면 된다 

 

DP

var tribonacci = function(n) {
    const arr = new Array(n).fill(0);
    
    arr[0] = 0;
    arr[1] = 1;
    arr[2] = 1;
    arr[3] = 2;
    
    for (let i = 4; i < n + 1; i++) {
        arr[i] = arr[i -1] + arr[i -2] + arr[i - 3];
    }
    
    return arr[n];
};

 

recursive하게 풀이 하려면 이전글에 지금과 똑같이 해주면 된다 

 

Leetcode에 챌린지가 있길래 이번에 참여해봤다 

2개 참여해서 총 4문제 풀었는데 이제 슬슬 미디움에 도전할 때가 된 것 같다 

 

챌린지 참여하면서 미디움 도전해봐야지 

 

반응형

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

 

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

 

난이도: easy 

DP

var fib = function(n) {
    const arr = new Array(n).fill(0);
    arr[0] = 0;
    arr[1] = 1;
    arr[2] = 1;
    
    for (let i = 3; i < n + 1; i++) {
        arr[i] = arr[i - 1] + arr[i - 2];
    }
    
    return arr[n]
};

 

 

Recursive

var fib = function(n) {
    if (n === 0) return 0;
    if (n === 1) return 1;
    
    return fib(n - 1) + fib(n - 2);
}

 

물론 효율은 DP로 풀이하는 것이 훨씬 좋다 

 

 

 

반응형

Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.

 

Example 1:

Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:
- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.
- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.
- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.
- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.

Example 2:

Input: nums = [1,2,3,4], k = 1
Output: 0
Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.

 

난이도: easy

 

같은 숫자인 두개의 index를 곱해서 k로 나누어 지는 경우를 구해라 

 

var countPairs = function(nums, k) {
    // map 생성 { number => [index] }
    const map = new Map();
    let count = 0;
    // for 문 -> map.get(number) ? [index].push : push(index)
    for (let i = 0; i < nums.length; i++) {
        const number = nums[i];
        const getItem = map.get(number);
        
        if (getItem) {
            for (let j = 0; j < getItem.length; j++) {
                const index = getItem[j];
                if ((index * i) % k === 0) count++;
            }
            getItem.push(i);
        } else {
            map.set(number, [i]);
        }
    }
    return count;
};

 

map을 생성해서 같은 숫자인지 확인 -> 곱해서 k로 나누어 떨어지는 확인 

 

두가지로 생각해서 풀이를 했다 hashMap을 사용해서 풀이 

 

언제쯤 easy에서 벗어날 수 있을까 

 

이중 for문으로 푼 경우가 더 효율이 좋은 걸 보고 내가 생각이 짧았구나 싶었다 

이래서 아직 medium은 벽이 느껴지나 보다 

 

 

반응형

+ Recent posts