Created
May 14, 2017 16:39
-
-
Save FireNeslo/562132f482d676e18294f195434f615c to your computer and use it in GitHub Desktop.
Structs
This file contains hidden or 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
var structure = (function () { | |
"use strict"; | |
function BaseStruct(values) { | |
for(var i= values.length-1; i>= 0; i--) { | |
this[i] = values[i] | |
} | |
} | |
BaseStruct.prototype.toJSON = function toJSON() { | |
var array = new Array(this.length) | |
for(var i = array.length-1; i >= 0; i--) { | |
array[i] = this[i] | |
} | |
return array | |
} | |
return function structure(properties, methods) { | |
function Struct(values) { | |
if(!(this instanceof Struct)) { | |
return new Struct(values) | |
} | |
BaseStruct.call(this, values) | |
} | |
Struct.prototype = Object.create(BaseStruct.prototype, { | |
length:{ get() { | |
return properties.length | |
}} | |
}) | |
if(typeof methods === 'object') { | |
Object.keys(methods).forEach(method => { | |
var descriptor = Object.getOwnPropertyDescriptor(methods, method) | |
Object.defineProperty(Struct.prototype, method, descriptor) | |
}) | |
} | |
properties.forEach((property, index) => { | |
Object.defineProperty(Struct.prototype, index, { | |
enumerable: false, | |
configurable: true, | |
get() { | |
return this[property] | |
}, | |
set(value) { | |
return this[property] = value | |
} | |
}) | |
}) | |
return Struct | |
} | |
}()) | |
var Person = structure(['name', 'age']) | |
var person = Person(['Per', 19]) | |
var CSV = { | |
parse(string, Value) { | |
var lines = string.split('\n') | |
if(typeof Value !== 'function') { | |
Value = structure(lines.shift().split(','), Value) | |
} | |
return lines.map(line => Value(line.split(','))) | |
}, | |
stringify(array) { | |
var properties = Object.keys(array[0]) | |
var result = [ properties.join(',') ] | |
for(var item of array) { | |
result.push(properties.map(property => item[property]).join(',')) | |
} | |
return result.join('\n') | |
} | |
} | |
CSV.parse(CSV.stringify([person, person]), Person) | |
.every(person => person instanceof Person) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment