UNPKG

basecamp-guide

Version:
83 lines (61 loc) 2.75 kB
// Dependecies var FileContent = (function() { // private vars var fileContent; // private methods var contentExist = function(contentToAdd) { var position = fileContent.search(makeRegExFrom(contentToAdd)); if (position >= 0) return true; return false; }; var makeRegExFrom = function(value) { return new RegExp(value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")); }; var writeContentAtPosition = function(position, content) { var part1 = fileContent.slice(0, position); var part2 = fileContent.slice(position); return part1 + content + part2; }; var searchNextPositionOf = function(searchRegExp, startPosition) { var contentToBeSearched = fileContent.slice(startPosition); return contentToBeSearched.search(searchRegExp) + startPosition; }; return { // public methods init : function(initFileContent) { fileContent = initFileContent; return this; }, get : function() { return fileContent; }, add : function(content, position) { if (position === undefined ) position = fileContent.length; if (contentExist(content)) return 'CONTENT_EXIST'; fileContent = writeContentAtPosition(position, content); return 'CONTENT_ADDED'; }, addAfter : function(afterText, content) { if (! contentExist(afterText)) return 'AFTER_TEXT_NOT_EXIST'; if (contentExist(content)) return 'CONTENT_EXIST'; var addPosition = fileContent.search(makeRegExFrom(afterText)) + afterText.length; fileContent = writeContentAtPosition(addPosition, content); return 'CONTENT_ADDED'; }, addBetween : function(startText, endText, content) { if (! contentExist(startText)) return 'START_TEXT_NOT_EXIST'; if (! contentExist(endText)) return 'END_TEXT_NOT_EXIST'; if (contentExist(content)) return 'CONTENT_EXIST'; var startPosition = fileContent.search(makeRegExFrom(startText)) + startText.length; var endPosition = searchNextPositionOf(makeRegExFrom(endText), startPosition); fileContent = writeContentAtPosition(endPosition, content); return 'CONTENT_ADDED'; }, replace: function(oldContent, content) { if (! contentExist(oldContent)) return 'CONTENT_TO_REPLACE_NOT_EXIST'; fileContent = fileContent.replace(makeRegExFrom(oldContent), content); return 'CONTENT_REPLACED'; } }; })(); module.exports = FileContent;