Gulp- Make sure file has comments in the beginning - javascript

I have multiple javascript files in a folder and I want to make sure that every file has comment in the beginning (that will explain the summary of file).
/*
This file will......
*/
function test () {
....
}
So is this possible using gulp-contains or something else?

I think this would be enough just to make sure if start of a file is the comment initial characters (/*)
gulp.src('./file.js')
.pipe(map(function(file, callback) {
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
if (startWithComment){
// DO YOUR CHORES
}
}))
Another approach is to split the initial text to make sure if it is a valid multi-line comment.
function startsWithValidMultiLineComment(str){
try{
return str.replace(/\n|\r/g, "").trim().split("/*")[1].split("*/")[1].length > 0
} catch (e){
return false;
}
}
Following this approach str.split("/*")[1].split("*/")[0] would be your comment text

By using the regex provided by #Sajjad in previous answer. I have managed to achieve my goal. I have used gulp-if and gulp-fail instead (I find it more flexible).
Here is how I do that:
var condition = function (file) {
sFile = require('path').parse(file.path).name;
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
return (!startWithComment);
}
gulp.task('taskName',
function() {
gulp.src('files/*.js')
.pipe(gulpIf(condition, fail(function () {
var message = 'Some message';
return message;
})));
});

Related

Error in Regex101 or my code? JavaScript / Node

I am currently doing an exercise that I got from my school. It's about regex but I am not sure if there is something wrong with my function or my regex code. We were told to use regex101.com to try things out.
in that site it looks like this and it all seems to work.
But in my file I get this.
Here is the code:
function isCheck(words) {
const check = /\Bche(ck|que)/;
return check.test('check', 'cheque');
}
So I am thinking that maybe there is something wrong in my function but I am not sure what that could be.
this is what its testing against
describe('The check-checker', () => {
it.only('should match check', () => {
const check = 'check';
assert.equal(matcher.isCheck(check), true);
});
it.only('should match cheque', () => {
const cheque = 'cheque';
assert.equal(matcher.isCheck(cheque), true);
});
Does anyone have any ideas?
I finally found it, for anyone else in a similar situation.
The function was wrong. I needed a parameter and to call on it in the function.
function isCheck(test) {
const check2 = /\b(check|cheque)\b/i;
if (check2.test(test)) {
return true;
}
return false;
}
module.exports.isCheck = isCheck;
There is the code.

Why aren't i successfully getting the embedded "if" in the second code section to do its job?

var checking_location = "none"
const getentitiesByType = (arr, type) => {
for (let i in arr) {
if (arr[i].type === type) {
checking_location = "exists"
return arr[i].entity
}
}
return null;
}
if (!meeting.location) {
if (checking_location != 'exists') {
rl.question('where is the location ', function(answer) {
// session.send("The location you gave:" answer);
rl.close();
session.send(answer)
// console.log(tryagain(answer, 'Calendar.Location'));
session.send(tryagain(answer, 'Calendar.Location'));
});
}
} else {
next();
}
What i'm trying to do here is to have a loop in the if (!meeting.location) if checking_location stays equal to none. Basically i want to check if a certain Json field exists, if it doesn't i want to keep asking the question in rl.question.My issues is that the code is only working the first time, then even if i give another input not containing the required field i don't get that question.Also note that this is not the entire code but it's more than enough to understand the possible issue spots in my implementation.
getentitiesByType needs to be called somewhere, simply assigning it to a variable will not make the function run: getentitiesByType(youArr, yourType).
Also, as a side note, instead of using string values for checking_location just rename the variable and use a boolean value. Ex: var hasLocation = false.

Get Filename from URL and Strip File Extension

I need to get just the filename without the extension from a url and can't quite get there.
Here's my url in question:
https://www.mealenders.com/shop/index.php/shop/solo-pack.html
Here's what I've tried:
function () {
var value={{Page Path}}.split("/");
return value.reverse()[0];
}
That almost gets me there as it returns "solo-pack.html". What else do I need to do to get rid of the ".html" for this?
Thanks in advance.
You can do the following using javascript. Pop returns the last element which is a string, and then you can use the replace function to get just the filename without .html on the end.
function getFilename () {
return {{ Page Path }}.split('/').pop().replace('.html', '');
}
I see that {{ Page Path }} is probably some templating language but you could modify the above script, to get the current URL and then get the filename as so.
function getFilename () {
return window.location.href.split('/').pop().replace('.html', '');
}
Furthermore you could make it more dynamic to handle any file extension with the following. You need to get the index of the period using indexOf and then sub string from the start of the filename up to the position of the period.
function getFilename () {
var filename = window.location.href.split('/').pop();
return filename.substr(0, filename.lastIndexOf('.');
}
function getFileName(url) {
return url.split("/").pop().split(".")[0];
}
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
console.log(getFileName(url));
function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
}
If you need to get rid of any extension, you can use .replace() with regular expression:
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
function getFilename (path) {
return path.toString().split('/').pop().replace(/\.\w+$/, '');
}
console.log(getFilename(url));
This will for example change test/index.html into index but index.php.default into index.php and also test.name.with.dots.txt -> test.name.with.dots
Short and sweet:
"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")
Returns:
solo-pack

Can someone help me understand the purpose of the Node.js code when using JavaScript on HackerRank?

I have a coding challenge coming up that will be using HackerRank, which I am unfamiliar with. I started trying to get familiar with it before I started and imagine my surprise when I saw this boilerplate-ish code in the editor!
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
The rest of the challenges on HR have slightly modified versions of this and I can't help but wonder what is really going on. It seems like there is some sort of text file that the editor is reading from and is therefore able to compare to my output?
I'd really appreciate any insight into this as I am pretty sure that I will have to write my own Node "boilerplate" when I do my coding challenge.
Thanks!
The code basically receives the information you need as input for the challenges. This particular one makes it so that the input comes through the same way the describe it in the challenge.
// Begin reading from stdin so the process does not exit. (basically reading from the command line)
process.stdin.resume();
//set the enconding for received data to ascii so it will be readable
process.stdin.setEncoding('ascii');
//declare variables to process the data
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
//if data is coming through, put it in the input_stdin string. keep receiving data until no more comes through
process.stdin.on('data', function (data) {
input_stdin += data;
});
//after the transmission when the end signal is received break the string up and push each new line (\n == new line) as an element into the array.
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
//gives you one element per line to work with.
function readLine() {
return input_stdin_array[input_currentline++];
}
Usually this code is followed by some more (below the comment line) where you already get variables assigned to have the data in a workable format.
There is another version of the code that doesn't deliver as bite sized chunks:
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
As you can see, the code is basically the same but some of the boiler plate 'making the input usable' is something you have to do in this one.
Just don't be confused. Every challenge I solve there, the first thing I do is console.log(input) or any other pre-created variable. it helps me knowing what is actually where.

Highlight HTML using Remarkable and Highlightjs

I'm having trouble getting the highlight function to execute when using Remarkable to highlight HTML code. I'm taking from the example here:
var md = new Remarkable({
html:true,
langPrefix:'lang-',
highlight: function (str, lang) {
alert('highlighting'); // never executes!
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, str).value;
} catch (err) {}
}
try {
return hljs.highlightAuto(str).value;
} catch (err) {}
return ''; // use external default escaping
}
});
var test = md.render('<code class="lang-js">var x = 1;</code>');
See fiddle
Remarkable works when you give it text written in markdown, not HTML. It generates the HTML for you. If you wanted to write out the HTML yourself, you don't need Remarkable ;)
So, your test line should look like this:
var test = md.render('``` js\nvar x = 1;\n```\n');
(normally, text is pulled from a text area, so you don't need the "\n" in there, you would just hit enter)
Here is the working fiddle:
https://jsfiddle.net/fhz9oma1/7/

Categories