Created
June 10, 2015 16:49
-
-
Save troutowicz/9d2d994fd3794df0ff7a to your computer and use it in GitHub Desktop.
ES6 class to stamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import stampit from 'stampit'; | |
import assert from 'assert'; | |
/** | |
* Get object of non-enum properties | |
*/ | |
function getNonEnum(target) { | |
const props = Object.getOwnPropertyNames(target); | |
const enumOnly = Object.keys(target); | |
let obj = {}; | |
props.forEach(function(key) { | |
var indexInEnum = enumOnly.indexOf(key); | |
if (indexInEnum === -1 && key !== 'constructor') { | |
obj[key] = target[key]; | |
} | |
}); | |
return obj; | |
} | |
/** | |
* Get object of enum properties | |
*/ | |
function getEnum(target) { | |
const props = Object.keys(target); | |
let obj = {}; | |
props.forEach(function(key) { | |
obj[key] = target[key]; | |
}); | |
return obj; | |
} | |
function convertClass(Class) { | |
const constructor = function() { | |
Object.assign(this, new Class()); | |
}; | |
const methods = getNonEnum(Class.prototype); | |
return stampit() | |
.enclose(constructor) | |
.methods(methods) | |
.static(getEnum(Class)); | |
} | |
/***************************************************/ | |
class Foo { | |
constructor() { | |
this.prop = 'foo' | |
} | |
static staticProp = 'foo' | |
method() { | |
return 'foo'; | |
} | |
} | |
const stamp = convertClass(Foo); | |
assert.equal(stamp.staticProp, 'foo'); | |
assert.equal(stamp().prop, 'foo'); | |
assert.equal(stamp().method(), 'foo'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment