3월, 2019의 게시물 표시

JavaScript 기본 상식 #2

Equality operator(동치 연산자, '==', '===')를 이해하기 값을 비교할 때, 사용하는 연산자로서, 어느 때, '=='와 '==='를 사용해야 하는지를 혼동하는 경우가 많다. 3 == '3' true '3' == new String('3') true 1 == true true null == undefined true 단! 아래 경우는 그렇지 않다. (주의!) 'true' == true fales 2 == true false null == true false 일반적으로 그냥 true인지 보기 위한 비교, 예를 들면, var a = 3; var b = '3'; a == b true 와 같이 값이 최소한 있냐는 관점에서 비교할 때는 문제가 되지 않는다. 하지만, 정확하게 그 값이 있는지 확인할 목적이라면, 이렇게 하면, 큰 낭패를 볼 수 있다. 예를 들면, 위 예에서, 다음을 입력하면 전혀 다른 결과를 가져오기 때문이다. var a = 3; var b = '3'; a += 1 b += 1 a == b false 그래서, 보통 값이 명확하고 형변환과 무관할 때는 '=='를 사용하고, 그렇지 않은 경우는 '==='를 사용하는 것이 좋다. var a = 3; var b = '3'; var c = '3'; a == b true a === b false a == '3' true a == 3 true a === '3' false a === 3 true b == c true b === c true b == 3 true b == '3' true b === '3' true

JavaScript 기본 상식 #1

null과 undefinded "JavaScript는 변수의 자료형의 결정 시점은 {할당할 때}이다." 정의 "undefined" 아직 자료형이 결정되지 않았다. 즉, "변수나 함수가 선언은 되었으나, 값을 할당하지는 않았다" 는 뜻이다. 주의할 것은, 아직 선언되지 않은 변수나 함수 등도  모두 undefined로 확인이 되나, 그렇다고, 변수나 함수가 선언되어 있다는 뜻은 아니다. "null" 이미 자료형이 결정되었다. 즉, "변수나 함수가 선언은 되었고, 값을 null로 할당했다" 는 뜻이다. 자료형 null: "object" undefined: "undefined" typeof null "object" typeof undefined "undefined" "void 0"과 비교 null: false undefined: true null === void 0 false undefined === void 0 true "null"과 "undefined" 비교 "{형변환}을 하느냐('=='), 안하느냐('===')에 따라 결과가 다르다." null == undefined true null === undefined false 추가. delete이후 값에 대한 확인 "{형변환}을 하느냐('=='), 안하느냐('===')에 따라 결과가 다르다." const arr1 = ['a1', 'a2', 'a3', 'a4', 'a5']; delete arr1[2]; true console.log(arr1); (5) ['a1&

MongoDB 설치 및 설정

MongoDB 설치 및 설정 Homebrew를 통해 설치한 경우로 설명한다. * 관련 링크: https://hitendert.wordpress.com/2013/08/24/steps-to-setup-mongodb-on-mac/ * 관련 링크: https://gist.github.com/tonypujals/9630872 * 관련 링크:  http://www.mongodbspain.com/en/2014/11/06/install-mongodb-on-mac-os-x-yosemite/ MongoDB 위치 변경 필요한 위치에 저장소를 생성한다. 로그 저장 위치도 포함 $ sudo mkdir -p /var/log/mongodb $ sudo mkdir -p /data/db $ sudo chown $('whoami') /data/db * 관련 링크: https://gist.github.com/tonypujals/9630872 명령으로 처리하는 방법 $ mongod --dbpath "/data/db" Configuration Files (mongod.conf) 파일 수정하기 $ sublime /usr/local/etc/mongod.conf systemLog:   destination: file   path: /var/log/mongodb/mongo.log   logAppend: true storage:   dbPath: /data/db <-- DB 위치(자신이 원하는 위치로 정할 수 있다.) net:   bindIp: 127.0.0.1 <-- 외부 IP를 허용하려면, "0.0.0.0"으로, local만 허용할 때는, "127.0.0.1" Configuration Files (mongod.conf) 간단 설명 # Store data at default /data/db dbpath = /data/db # Append l

Homebrew v2.x에서 Node를 NPM 없이 설치하기

Homebrew v2.x에서 Node를 NPM 없이 설치하기 기본적으로 없다. 우선 내가 만들어낸 편법만 있다. Homebrew의 원칙이 변경되었다. 이런 하위 options를 제공함으로서, 다양한 부가 오류에 대한 대응이 어렵다는 이유에서다. $ brew install node --without-npm ... Error: invalid option: --without-npm 그렇지만, 방법이 전혀 없는 것은 아니다. 직접적인 방법이 없을 뿐. Homebrew v1.x로 설치하는 방법은 아래와 같다. ( Mac OS X Homebrew로 NodeJS를 설치했을 때, NPM package오류 해결 방법 ) 주의! 아래를 실행하기에 앞서서, 반드시 위 링크대로 특정 위치로 NPM의 설치 위치를 정해줘야 한다. $ brew install node $ curl -L https://www.npmjs.com/install.sh | sh $ ls -la $(which node) lrwxr-xr-x 1 keiches staff 31 Feb 19 23:29 /usr/local/bin/node -> ../Cellar/node/11.10.0 /bin/node $ rm -Rf /usr/local/bin/ ../Cellar/node/11.10.0 /libexec/lib/node_modules/npm

Webpack copy-webpack-plugin ignore 사용할 때 주의 점(Important point when using the option "ignore" of the "copy-webpack-plugin")

Webpack copy-webpack-plugin ignore 사용할 때 주의 점(Important point when using the option "ignore" of the "copy-webpack-plugin") "copy-webpack-plugin"의 "ignore"가 정상 동작(내 생각에... -.-;;; ) 안해서, 도대체 뭘까 한참을 고민한 적이 있다. 다음을 주의하면서, ignore를 작성하면 정상적으로 동작한다. "path를 ignore할 경우: "from"을 기준으로 그 다음 path 부터 나열해야 한다." Path 구성 ~/my_app/resources/images/images # 모두 복사 ~/my_app/resources/images/images.no-copy # 모두 복사 안함 ~/my_app/resources/images/images.must/title.no-copy # 모두 복사 안함 webpack config (webpack.config.js) module.exports = { entry: { }, ... plugins: [ new CopyPlugin( [ { from: path.resolve('my_app', 'images'), to: path.resolve('my_app', 'images'), // or to: '', toType: 'dir', // optional ignore: [ 'images.no-copy', // "my_app/images/images.no-copy" 이하 모두("**/*.*") 복사 안함. 주

중복을 제거하여 교집합 구하기 (Intersection of arrays with duplicate values)

중복을 제거하여 교집합 구하기 (Intersection of arrays with duplicate values) 단순화 const source1 = [1, 2, 3, 4, 5, 7]; const source2 = [2, 3, 4]; source1.filter(value => source2.indexOf(value) !== -1); => [2, 3, 4] 단순화의 한계: 중복이 있는 경우, 황당한 결과를 전달하게 된다. const source1 = [1, 2, 3, 2, 4, 5, 3, 3, 7]; const source2 = [2, 3, 2, 4, 5, 3]; source1.filter(value => source2.indexOf(value) !== -1); => [2, 3, 2, 4, 5, 3, 3] 단순화 개선 버전 (ES6 "Set" 필요) const source1 = [1, 2, 3, 2, 4, 5, 3, 3, 7]; const source2 = [2, 3, 2, 4, 5, 3]; // pattern #1 const setSource2 = new Set(source2); const source3 = [...new Set(source1.filter(value => setSource2.has(value)))]; // pattern #2 const source3 = [...new Set(source1.filter(value => (source2.findIndex(value2 => (value === value2)) > -1)))] => [2, 3, 4, 5] 참고 ( StackOverflow ) [...new Set()]는 Array.from(new Set()) 와 동일하다. Class "Set"는 입력된 요소를 유일한 값만 추려서 가지고 있게 된다. new Set([1, 2, 2, 3]) => {1, 2, 3}
JavaScript Class 상속하는 방법 ES5 Class 상속 // 기본 클래스 function CalcAdd(options) { // this.title = options && options.title || 'Calc Add'; this.calculate = () => { console.log(this.constructor.name, "!!!!!"); }; } CalcAdd.create = function (options) { return new CalcAdd(options); }; // 프로토타입 CalcAdd.prototype.add = function add() { // }; // 상속받은 클래스 function CalcAddWithDivide(options) { // const _this = CalcAdd.apply(this, { title: 'Calc Add With Divide' }) || this; // super(arguments); 와 동일 _this.calculate = function() { console.log(this.constructor.name, "~~~~~~"); }; return _this; }; CalcAddWithDivide.prototype = Object.create(CalcAdd.prototype, { constructor: { value: CalcAdd, enumerable: true, writable: true, configurable: true } }); CalcAddWithDivide.prototype.constructor = CalcAddWithDivide; // 추가 프로토타입 CalcAddWithDivide.prototype.divide = function divide() { // }; ES

배열에서 유일한 값만 추리기 (Get only unique values ​​in an array)

배열에서 유일한 값만 추리기 (Get only unique values ​​in an array) 기본 알고리즘 const source = [1, 2, 3, 2, 4, 5, 3, 3, 7]; for (let indexLeader = 0, lengthLeader = source.length; indexLeader < lengthLeader; indexLeader += 1) { // console.group(`leader index${indexLeader}`, source[indexLeader], source); for (let indexFollower = indexLeader + 1, lengthFollower = source.length; indexFollower < lengthFollower; indexFollower += 1) { // console.log('follower', indexFollower, source[indexFollower]); if (indexLeader === indexFollower) continue; if (source[indexLeader] === source[indexFollower]) { // console.log('-deleted', indexFollower, source[indexFollower], source); source.splice(indexFollower, 1); // console.log('*after deleted', indexFollower, source); indexLeader -= 1; indexFollower -= 1; lengthLeader -= 1; lengthFollower -= 1; } } // console.groupEnd(`index${indexLeader}`); } => [1, 2, 3, 4, 5, 7]

Webpack "html-webpack-plugin" 사용팁

Webpack "html-webpack-plugin" 사용팁 html-webpack-plugin 을 이용하여, 작업하다보니 2가지 사용 방법이 궁금해졌다. 1번. html-webpack-plugin loader를 교체할 수 없나? 방법) webpack.config.js const HtmlPlugin = require('html-webpack-plugin'); ... const webpackConfigs = { plugins: [ new HtmlPlugin({ // 원래 코드 // template: 'index.ejs', // 변경할 코드 template: `${path.resolve( __dirname, 'html-my-loader', 'index.js' )}?param1&param2=foo&param3=bar!index.ejs` }) ] }; html-my-loader/index.js const loaderUtils = require('loader-utils'); module.exports = function myLoader(source) { const options = loaderUtils.getOptions(this) || {}; ... return source.replace(options.from, options.to); }; 2번. block 제거 혹은 string replace 와 같은 것을 선행적으로 적용하고 나서 처리되게 할 수 없나? webpack.config.js const HtmlPlugin = require('html-webpack-plugin'); ... const webpackConfigs = { module: { rules: [