본문 바로가기
javascript

[LEARN-JS] String, Jest

by rami_ 2024. 7. 23.

javascript의 string method를 더 잘 알아보기 위해 직접 구현후 테스트코드를 짰다.

이 기록은 구현 중 알게 된 것을 모아둔 것이다.

https://github.com/rami0617/learn-js

 

GitHub - rami0617/learn-js: To study javascript, I implement the methods myself by referring to the MDN documentation.

To study javascript, I implement the methods myself by referring to the MDN documentation. - rami0617/learn-js

github.com


 

1. concat method

  1) concat을 사용하는것보다 할당 연산자(+, +=)를 사용하는 것이 성능이 더 좋다고 한다.

    - 해당 링크에서는 concat, +, join의 속도를 측정하는데 +가 가장 성능이 좋은것으로 나타났다.

 

2. substring vs slice

  1) substring과 slice는 거의 비슷하지만 인자로 음수가 들어왔을 때 다르게 작동한다.

  2) substring은 음수나 NaN가 들어올 경우 0으로 간주한다.

  3) substring은 indexStart가 indexEnd보다 클 경우 둘을 swap한다.

const foo = 'foo';
foo.substring(-1) //'foo' 
foo.substring(3,1) //'oo'

foo.slice(-1) //'o'
foo.slice(3,1) //''

 


Jest

1. expect안에서 바로 코드를 실행시킬 경우 expect에는 도달이 되지 않으므로, expect 구문 내에서 함수를 화살표 함수로 감싼다.

describe("13. String.prototype.repeat", () => {
  const string = "hello";

  test("1) if count is negative number, return range error.", () => {
    expect(() => string.repeat(-1)).toThrow(RangeError);
    expect(string.repeat(-1)).toThrow(RangeError);
  });
});

 

'javascript' 카테고리의 다른 글

[LEARN-JS] Array method - 기존 배열 변경 유무에 따라 나누기  (0) 2024.08.12
[LEARN-JS] Array  (0) 2024.08.06
closure  (0) 2024.03.27
scope  (1) 2024.03.26
hoisting  (0) 2024.03.26