기본 콘텐츠로 건너뛰기

라벨이 object인 게시물 표시

[삽질주의] js에선 object를 어떻게 확장하는가? .map 만들기.

http://spectrum.egloos.com/5580651 옛날 글 소환인데 map을 object 에서도 한번 해볼려고 이렇게 시도해 보았다. > Object.defineProperty(Object.prototype, "map", {value: function(fn) {   for (idx in this) this[idx]=fn(this[idx]); return this; } }); > q={a:1, b:2} > q.map(v=>v+1) Object {a: 2, b: 3} ECMA5부터 Object.defineProperty 를 쓸 수 있고 prototype 삽질을 막을 수 있다. > q={a:1, b: {c: 2, d: 4}} > Object.defineProperty(Object.prototype, "map", {value: function(fn) {   let map=(f,arr)=>{     for (idx in arr)         arr[idx]=typeof arr[idx]==="object" && map(f,arr[idx]) || f(arr[idx]);     return arr;   }   return map(fn, this); }}); > q.map(v=>v+1) Object {a: 2, b: Object} a:2 b:Object   c:3   d:5 뭐 의도한대로 잘 나오긴 한다. value 인 경우만 fn을 실행하고 object면 재귀를 사용한다. 뭐 array만 들어와도 이건 망하겠네; google 에서 왜 [[a,2], [b,3]] 따위 자료 구조를 썼는지 어느정도 이해가 된다.

오늘의 코드 - Excel 에서 Collection 까지 (feat. dot2obj)

Meteor.startup ->   if Tours.find().count() is 0     addDefault = (v)->       v.createdAt = Date.now()       v     dot2obj = (obj)->       for k,v of obj         idxes = k.split '.'         if idxes.length>0           delete obj[k]           idxes.reduce (a,b,ci,ar)->             a[b] = ar.length-1 is ci and v or a[b] or {}           , obj       obj     excel = new Excel 'xlsx'     workbook = excel.read new Buffer Assets.getBinary "fixtures.xlsx"     fixtures = excel.utils.sheet_to_json workbook.Sheets['Sheet1']     Tours.insert addDefault dot2obj obj for obj in fixtures     console.log "Tours collection initiated." 이런 코드를 만들었다. Tours 라는 collection이 비어있으면 excel 파일을 읽어서 (...

Coffeescript 에서 Array와 Object를 다루는 방법

자바스크립트를 하다보면 JSON Object와 Array를 처리할 일이 참 많다. http://spectrumdig.blogspot.com/2012/01/array-method-iteration.html Array 의 경우 위의 글을 참조. 그런데 Object는 Array처럼 다양하고 Chaining 이 가능한 방법이 없다. 기껏해야 for (var obj in jsonObject) 정도. 게다가 속도문제도 있어서 ( http://jsperf.com/for-vs-foreach/9  참조) 가독성과 코드 단순화도 좋지만 요즘같이 Rich Web Application + Mobile Web 시대에 쓰기엔 효율이 나쁜 방법이긴 하다. coffeescript 의 경우 object 와 array 에 대해 어느정도 비슷한 처리방식을 제안한다. array : <statement> for <variable> in <array> object : <statement> for <variable>,{<variable>} in <object> 와 같은 형식이다. object 의 경우 variable 로 key, value 형식을 쓸 수 있는데 value 를 생략할 수 있다. 예를 들면 아래와 같다. console.log arr for arr in [1,2,3,4,5] console.log k,v for k,v of a:1, b:2, c:3 물론 당연히 두개를 혼합해서 쓸 수도 있다. console.log k,v for k,v of obj for obj in [ {a:1, b:2}, {a:3, b:4 }, {a:1, c:4} ] 결과는 아래와 같다. a 1 b 2 a 3 b 4 a 1 c 4 재미있는 점은 둘 다 공히 when 이라는 조건절을 넣어서 filter 를 할 수 있다. console.log k,v for k,v of a:1,...

왜 object에 prototype을 쓰지 않나?

http://triin.net/2009/09/13/Why_exactly_is_Object.prototype_verboten 이유는 이렇다. prototype 에 method 를 정의하면 자기 자신도 해당 object 에 카운트가 된다. 무슨말이냐? object (array포함) 의 key와 value를 보기 위해 종종 아래와 같이 해본다. var ages = {  John: 10,  Mary: 28,  Alice: 16}; 일때 (function(obj){ for (idx in obj) { console.log(idx+':'+obj[idx]) }})(ages)  이렇게 떠 보면 John:30 Mary:30 Alice:30 뭐 이렇게 나오겠지. 그럼 아예 object 에 이걸 prototype 해서 그냥 method 로 만들지 싶어 Object.prototype.printObject=function(){ for (idx in this) { console.log(idx+':'+this[idx]) }}; 요따우로 해주면 ages.printObject() > John:10 > Mary:20 > Alice:30 > printObject:function (){ for (idx in this) { console.log(idx+':'+this[idx]) }} 망한다. 다시 이야기 하지만 자기 자신도 객체의 일부가 되니까. 그래서 쓰지말라는 것이다. hasOwnProperty를 사용해서 피해가는 방법도 있겠지만 다른 문제가 있다. 자세한 설명은 생략한다. 왜 그런지 알고 싶으면 본문 봐라. (난 알고싶지 않아서 안봤다. 안쓸거니까 우왕ㅋ) 결론은 이거다. defineProperty 를 사용하자. ECMAScript 5 스펙이다. 하지만 망할 IE7 에선 안되겠지 http:/...