blob: 3a084b3100113caf13f7622f106e680204570595 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
var is = require('is');
var SummaryArticle = require('../../models/summaryArticle');
var mergeAtLevel = require('./mergeAtLevel');
var indexArticleLevels = require('./indexArticleLevels');
/**
Returns a new Summary with the article at the given level, with
subsequent article shifted.
@param {Summary} summary
@param {Article} article
@param {String|Article} level: level to insert at
@return {Summary}
*/
function insertArticle(summary, article, level) {
article = SummaryArticle(article);
level = is.string(level)? level : level.getLevel();
var parent = summary.getParent(level);
if (!parent) {
return summary;
}
// Find the index to insert at
var articles = parent.getArticles();
var index = getLeafIndex(level);
// Insert the article at the right index
articles = articles.insert(index, article);
// Reindex the level from here
parent = parent.set('articles', articles);
parent = indexArticleLevels(parent);
return mergeAtLevel(summary, parent.getLevel(), parent);
}
/**
@param {String}
@return {Number} The index of this level within its parent's children
*/
function getLeafIndex(level) {
var arr = level.split('.').map(function (char) {
return parseInt(char, 10);
});
return arr[arr.length - 1] - 1;
}
module.exports = insertArticle;
|