diff options
author | Soreine <nicolas@gitbook.com> | 2016-05-03 16:02:58 +0200 |
---|---|---|
committer | Soreine <nicolas@gitbook.com> | 2016-05-03 16:02:58 +0200 |
commit | 3fc90554f5e7e6ff2fb4f023319799e1e8f81454 (patch) | |
tree | dc34d87ba50d004c9fac610a370432ae340ad498 /lib/modifiers/summary/mergeAtLevel.js | |
parent | 4ebe28faaebb8752107ef6cfa6253f7b6f8a2a86 (diff) | |
download | gitbook-3fc90554f5e7e6ff2fb4f023319799e1e8f81454.zip gitbook-3fc90554f5e7e6ff2fb4f023319799e1e8f81454.tar.gz gitbook-3fc90554f5e7e6ff2fb4f023319799e1e8f81454.tar.bz2 |
Add tests, and fixes.
Diffstat (limited to 'lib/modifiers/summary/mergeAtLevel.js')
-rw-r--r-- | lib/modifiers/summary/mergeAtLevel.js | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/lib/modifiers/summary/mergeAtLevel.js b/lib/modifiers/summary/mergeAtLevel.js new file mode 100644 index 0000000..9a95ffc --- /dev/null +++ b/lib/modifiers/summary/mergeAtLevel.js @@ -0,0 +1,75 @@ + +/** + Edit a list of articles + + @param {List<Article>} articles + @param {String} level + @param {Article} newArticle + @return {List<Article>} +*/ +function editArticleInList(articles, level, newArticle) { + return articles.map(function(article) { + var articleLevel = article.getLevel(); + + if (articleLevel === level) { + // it is the article to edit + return article.merge(newArticle); + } else if (level.indexOf(articleLevel) === 0) { + // it is a parent + var articles = editArticleInList(article.getArticles(), level, newArticle); + return article.set('articles', articles); + } else { + // This is not the article you are looking for + return article; + } + }); +} + + +/** + Edit an article in a part + + @param {Part} part + @param {String} level + @param {Article} newArticle + @return {Part} +*/ +function editArticleInPart(part, level, newArticle) { + var articles = part.getArticles(); + articles = editArticleInList(articles, level, newArticle); + + return part.set('articles', articles); +} + + +/** + Edit an article, or a part, in a summary. Does a shallow merge. + + @param {Summary} summary + @param {String} level + @param {Article|Part} newValue + @return {Summary} +*/ +function mergeAtLevel(summary, level, newValue) { + var levelParts = level.split('.'); + var partIndex = Number(levelParts[0]) -1; + + var parts = summary.getParts(); + var part = parts.get(partIndex); + if (!part) { + return summary; + } + + var isEditingPart = levelParts.length < 2; + if (isEditingPart) { + part = part.merge(newValue); + } else { + part = editArticleInPart(part, level, newValue); + } + + parts = parts.set(partIndex, part); + return summary.set('parts', parts); +} + + +module.exports = mergeAtLevel; |