Skip to content

Commit

Permalink
Complete getElementsByClassName in javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Feb 17, 2015
1 parent 8f817f1 commit 6307e32
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
31 changes: 31 additions & 0 deletions key-concepts.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,4 +751,35 @@ var once = function (fn, x) {
return fn.apply(this, args);
}
};
};

/*
* Get Elements by Class Name
* Implement the `getElementsByClassName(element, className)` function in Javascript
*/

var getElementsByClassName = function (className, element) {
element = element || document.body;

var inner = function (node, result) {
// check if current node has the class name
if (node.className.split(' ').indexOf(className) !== -1) {
// if it does, add the current node to result
result.push( node );
}

// determine whether current node has children
var children = Array.prototype.slice.call(node.children);
// if it doesn't then return result
// if it does:
// for each child, invoke inner on the child and a new empty array
// the returned value will be an array which should be concatenated to
// the current scope's result array

return children.reduce(function (acc, child) {
return result.concat( inner(child, []) );
}, result);
};

return inner(element, []);
};
6 changes: 2 additions & 4 deletions key-concepts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,9 @@ def create_string_hash(string)
end

def convert_to_data_structure(hash)
result = []
hash.each do |key, value|
result << [key, value]
hash.reduce([]) do |acc, arr|
acc << arr
end
result
end

#
Expand Down

0 comments on commit 6307e32

Please sign in to comment.