Skip to content

Commit

Permalink
refactor out forEachObject and forEachAttribute
Browse files Browse the repository at this point in the history
  • Loading branch information
Ola Holmström committed Feb 25, 2015
1 parent c8f2a99 commit 60f70cf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
2 changes: 2 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
* setAttribute
* cloneNode
* expand conversion combinators
* add benchmarks
32 changes: 12 additions & 20 deletions lib/Element/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,6 @@ var arrayInstanceOf = function (arr, Class) {
return arr instanceof Array && (arr.length === 0 || arr[0] instanceof Class);
};

var forEachObject = function (obj, fn) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) { continue; }
fn(key, obj[key]);
}
};

// validate
var validateType = function (type, validTypes) {
var elTypes = INHERIT[type];
Expand Down Expand Up @@ -81,7 +74,9 @@ var Element = module.exports = function (parentElement, parentAttribute, ast) {
}

// copy ast information onto object
forEachObject(ast, function (attr, value) {
Object.keys(ast).forEach(function (attr) {
var value = ast[attr];

if (typeof value === "object") {
if (value instanceof Array) {
if (value.length === 0) {
Expand Down Expand Up @@ -120,20 +115,11 @@ var Element = module.exports = function (parentElement, parentAttribute, ast) {
}.bind(this));
};

// private
Element.prototype._forEachAttribute = function (fn) {
var exclude = ["parentElement", "parentAttribute"];

forEachObject(this, function (attr, value) {
if (exclude.indexOf(attr) === -1) { fn(attr, value); }
});
};

// children
Element.prototype.childElements = function () {
var children = [];

forEachObject(ATTR[this.type], function (attr) {
Object.keys(ATTR[this.type]).forEach(function (attr) {
var value = this[attr];
if (arrayInstanceOf(value, Element)) {
children = children.concat(value);
Expand Down Expand Up @@ -322,7 +308,13 @@ Element.prototype.replaceChild = function (newChild, oldChild) {
Element.prototype.outerAST = function () {
var element = {};

this._forEachAttribute(function (attr, value) {
element.type = this.type;
element.loc = this.loc;
element.comments = this.comments;

Object.keys(ATTR[this.type]).forEach(function (attr) {
var value = this[attr];

if (arrayInstanceOf(value, Element)) {
element[attr] = value.map(function (v) {
return v.outerAST();
Expand All @@ -336,7 +328,7 @@ Element.prototype.outerAST = function () {
}

element[attr] = value;
});
}.bind(this));

if (this.recastPrelude !== null && this.parentElement === null) {
this.recastPrelude.program = element;
Expand Down

0 comments on commit 60f70cf

Please sign in to comment.