Skip to content

Instantly share code, notes, and snippets.

@ushiboy
Last active December 28, 2015 17:49
Show Gist options
  • Save ushiboy/7538347 to your computer and use it in GitHub Desktop.
Save ushiboy/7538347 to your computer and use it in GitHub Desktop.
車輪づくり。 ArrayやObjectの中までチェックするのどうしよう?
describe('class', function() {
var clazz = require('../src/class').clazz,
User = clazz('User', {
id : Number,
name : String,
birthday : Date,
owner : Boolean,
greet : function() {
return 'Hello ' + this.name();
}
});
it('should to be create class', function() {
var user = new User(),
day = new Date();
user.id(12345);
expect(user.id()).toBe(12345);
expect(function() {
user.id('1234');
}).toThrow();
user.name('test');
expect(user.name()).toBe('test');
expect(function() {
user.name(1234);
}).toThrow();
user.birthday(day);
expect(function() {
user.birthday('2013-12-31');
}).toThrow();
expect(user.birthday()).toBe(day);
user.owner(true);
expect(user.owner()).toBe(true);
expect(function() {
user.owner(1);
}).toThrow();
user._ngprop = 'NG';
expect(JSON.stringify(user)).toBe(
'{' +
'"id":12345,'+
'"name":"test",'+
'"birthday":"' + day.toJSON() + '",'+
'"owner":true' +
'}');
expect(user.greet()).toBe('Hello test');
expect(User.toString()).toBe('function User() { [user code] }');
});
});
!function(global) {
var toString = Object.prototype.toString;
function isDate(val) {
return toString.apply(val) === '[object Date]';
}
var isArray = Array.isArray;
function isString(val) {
return typeof(val) === 'string';
}
function isNumber(val) {
return typeof(val) === 'number';
}
function isBoolean(val) {
return typeof(val) === 'boolean';
}
function isObject(val) {
return !isArray(val) && !isDate(val);
}
var typeMatcher = {
'string' : isString,
'number' : isNumber,
'boolean' : isBoolean,
'date' : isDate,
'array' : isArray,
'object' : isObject
};
function clazz(className, config) {
var fn = function() {};
function decorator(config) {
var methods = {},
props = {},
key, type, value, tmp;
for (key in config) {
if (config.hasOwnProperty(key)) {
value = config[key];
tmp = value.toString().match(/function\s(.+)\(/);
type = tmp === null ? 'function' : tmp[1].toLowerCase();
if (type === 'function') {
methods[key] = value;
} else {
props[key] = true;
methods[key] = (function(key, matcher) {
return function(value) {
if (arguments.length === 0) {
return this['_' + key];
} else {
if (matcher(value)) {
this['_' + key] = value;
} else {
throw new Error('Argument Type Error');
}
}
};
})(key, typeMatcher[type]);
}
}
}
methods.toJSON = function() {
var key,
ret = {};
for (key in props) {
ret[key] = this['_' + key];
}
return ret;
};
return methods;
}
fn.prototype = decorator(config);
fn.toString = function() {
return 'function ' + className + '() { [user code] }';
};
if (typeof(module) !== undefined) {
module.exports = {
clazz : clazz
};
}
}(this.self || global);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment