From e09b1f797d646e240e405831a9ddccd21ca4b3f9 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 20 Nov 2016 12:15:39 +0000 Subject: Add getDescendants and getDescendantsOfType to tranforms --- lib/transforms.js | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) (limited to 'lib/transforms.js') diff --git a/lib/transforms.js b/lib/transforms.js index 5078387..22be1af 100644 --- a/lib/transforms.js +++ b/lib/transforms.js @@ -1,6 +1,10 @@ var _ = require("underscore"); -exports.paragraph = function(transform) { +exports.paragraph = paragraph; +exports.getDescendantsOfType = getDescendantsOfType; +exports.getDescendants = getDescendants; + +function paragraph(transform) { function transformElement(element) { if (element.children) { var children = _.map(element.children, transformElement); @@ -14,4 +18,30 @@ exports.paragraph = function(transform) { return element; } return transformElement; -}; +} + + +function getDescendantsOfType(element, type) { + return getDescendants(element).filter(function(descendant) { + return descendant.type === type; + }); +} + +function getDescendants(element) { + var descendants = []; + + visitDescendants(element, function(descendant) { + descendants.push(descendant); + }); + + return descendants; +} + +function visitDescendants(element, visit) { + if (element.children) { + element.children.forEach(function(child) { + visitDescendants(child, visit); + visit(child); + }); + } +} -- cgit v1.2.3