Given the following:
require('babel-core').transform('3').code
Is there a way to get this to return 3 (an expression) instead of 3; (a statement)?
I've tried:
Searching the web and various sites for 'babel expression', 'babel transpile expression', and the like.
Passing (3), but that also was transformed into 3;.
Poking the babel internals to figure out what's going on, but I don't know enough about how it works to sort this out.
Passing the option minified: true, which claims to remove the trailing semicolon but doesn't actually seem to do anything.
Right now I'm using .replace(/;$/, ''), which works but seems absurd and error-prone.
#loganfsmyth provided the missing link on BabelJS.slack -- parserOpts.allowReturnOutsideFunction. Here's the code I came up with:
const babel = require('babel-core');
let script = 'return ((selector, callback) => Array.prototype.map.call(document.querySelectorAll(selector), callback))("#main table a.companylist",a => a.innerText)';
let transform = babel.transform(script, {
ast: false,
code: true,
comments: false,
compact: true,
minified: true,
presets: [
['env', {
targets: {
browsers: ['> 1%', 'last 2 Firefox versions', 'last 2 Chrome versions', 'last 2 Edge versions', 'last 2 Safari versions', 'Firefox ESR', 'IE >= 8'],
}
}]
],
parserOpts: {
allowReturnOutsideFunction: true,
}
});
let code = `return function(){${transform.code}}()`;
Output:
return function(){"use strict";return function(selector,callback){return Array.prototype.map.call(document.querySelectorAll(selector),callback)}("#main table a.companylist",function(a){return a.innerText});}()
My input script looks a bit funny just because of how I generated it, but you can see that it transformed those arrow expressions into regular functions and the whole thing is still an expression.
N.B. you may want to modify that last line to something like
let code = `(function(){${transform.code}})()`;
depending on your needs. I needed mine to be returned.
Related
Is there any way to format the JSON logged through console.log in the terminal?
I'm logging a lot of debug data and if the the logged data exceeds a certain length, the terminal logs it prettified in many lines. I'd like to change it to log in one line, no matter the length of the data. Is there any way to do that?
In summary, I want to change this log style:
[12:34:56][DEBUG][CODE] - {
data: {
action: 'action',
url: '/path/to/my/api?variableOne=valueOne&variableTwo=valueTwo'
}
}
To this log style:
[12:34:56][DEBUG][CODE] - { data: { action: 'action', url: '/path/to/my/api?variableOne=valueOne&variableTwo=valueTwo' } }
Is there any way to format the JSON logged through console.log in the terminal?
Yes there is. Create a custom console object. See the docs for how to do that and what options you can specify. In particular, see also the inspectOptions docs.
The particular inspectOptions option you are looking for are breaklength and compact:
breakLength: <integer> The length at which input values are split across multiple lines. Set to Infinity to format the input as a single line (in combination with compact set to true or any number >= 1). Default: 80.
compact: <boolean> | <integer> Setting this to false causes each object key to be displayed on a new line. It will break on new lines in text that is longer than breakLength. If set to a number, the most n inner elements are united on a single line as long as all properties fit into breakLength. Short array elements are also grouped together. For more information, see the example below. Default: 3.
So since you asked
I'd like to change it to log in one line, no matter the length of the data
Then you probably want to do something like this:
const { Console } = require('node:console')
console = new Console({
stdout: process.stdout,
stderr: process.stderr,
// ignoreErrors, colorMode, groupIndentation
inspectOptions: {
// ...
breakLength: Infinity,
compact: true,
// ...
}
});
And then you can test it with console.log({a:1,b:2,c:3,hello:"world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"});.
You can also just use the util.inspect function on specific objects you want to make a formatted string for, and then do console.log on the default global console object, passing the returned string.
I am developing an extension for visual studio code using language server protocol, and I am including the support for "Go to symbol in workspace". My problem is that I don't know how to select the matches...
Actually I use this function I wrote:
function IsInside(word1, word2)
{
var ret = "";
var i1 = 0;
var lenMatch =0, maxLenMatch = 0, minLenMatch = word1.length;
for(var i2=0;i2<word2.length;i2++)
{
if(word1[i1]==word2[i2])
{
lenMatch++;
if(lenMatch>maxLenMatch) maxLenMatch = lenMatch;
ret+=word1[i1];
i1++;
if(i1==word1.length)
{
if(lenMatch<minLenMatch) minLenMatch = lenMatch;
// Trying to filter like VSCode does.
return maxLenMatch>=word1.length/2 && minLenMatch>=2? ret : undefined;
}
} else
{
ret+="Z";
if(lenMatch>0 && lenMatch<minLenMatch)
minLenMatch = lenMatch;
lenMatch=0;
}
}
return undefined;
}
That return the sortText if the word1 is inside the word2, undefined otherwise. My problem are cases like this:
My algorithm see that 'aller' is inside CallServer, but the interface does not mark it like expected.
There is a library or something that I must use for this? the code of VSCode is big and complex and I don't know where start looking for this information...
VSCode's API docs for provideWorkspaceSymbols() provide the following guidance (which I don't think your example violates):
The query-parameter should be interpreted in a relaxed way as the editor will apply its own highlighting and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the characters of query appear in their order in a candidate symbol. Don't use prefix, substring, or similar strict matching.
These docs were added in response to this discussion, where somebody had very much the same issue as you.
Having a brief look at VSCode sources, internally it seems to use filters.matchFuzzy2() for the highlighting (see here and here). I don't think it's exposed in the API, so you would probably have to copy it if you wanted the behavior to match exactly.
I'm using the prettier-vscode extension to format my js code, but flow annotations are formatted in a weird way with lots of extra space:
const handleResponse = async function < T > ( // <-- should be function<T>(
response,
url: string,
options: responseOptions = {}
): Promise < T | null > { // <-- should be Promise<T|null> {
or Promise<T | null> {
I've looked around in all the places I could think of to see what config I need to change to get this working, but I can't find anywhere that seems to affect the spacing in te above case.
There's also some weirdness going on with multi-line ternary statements, but I don't think that's related to flow:
const WORKORDERS_BASE_URL =
WORKORDERS_PORT === '80' ? // <-- I'd prefer if ? and : were on the next line
`http://${WORKORDERS_HOST}` : // <-- on same indentation level as above - I want one more
`http://${WORKORDERS_HOST}:${WORKORDERS_PORT}` // <-- same here, I want more indentation
The worst case of them all is this change, which happens when I format the document:
Promise<?T>
// becomes
Promise<<?T>
i.e. it actually breaks my code!
Where should I look for config that controls these things?
I'm trying to invoke a calendar with every day blocked excepting Thursdays.
Some Thursdays will be blocked, so I use daysOfWeekDisabled and disableDate.
jQuery('.custom-calendar-2').datetimepicker({
format: "dd/mm/yyyy",
daysOfWeekDisabled: [0,1,2,3,5,6],
useCurrent: true,
inline: true,
/*beforeShowMonth: function (date) {
if (date.getMonth() == 8) {
return false;
}
},*/
defaultDate: null,
minDate: moment().add(1, 'days'),
disabledDates: [
moment('04/07/2016', 'MM/DD/YYYY'),
moment('04/21/2016', 'MM/DD/YYYY')
],
//toggleActive: true
});
If I comment the line
moment('04/07/2016', 'MM/DD/YYYY'),
my calendar works. I'm trying to debug this but I just don't get it. The console says:
Tried 7 times to find a valid date
How I can solve that error?
EDIT:
I've digged into the library. On line 1648 there is this snippet:
if (tries === 7) {
throw 'Tried 7 times to find a valid date';
}
Changing the number of tries to something bigger like 14 just does the work. I get the idea of avoid some kind of infinite loop, but this way you can't do a basic operation like blocking the current week.
I wonder if there is another better way that modifying the library myself/monkey patching. Or this should be directly patched into the repository?
You could use keepinvalid = true, when you try to set disabled days from the calendar.
https://eonasdan.github.io/bootstrap-datetimepicker/Options/#keepinvalid
I've sent a pull request for a temporal fix. https://github.com/Eonasdan/bootstrap-datetimepicker/pull/1558
I really love the autofromat feature. I makes your code more readable and in case of JavaScript tells you, when there are synatcs errors (missing brackets etc.).
However sometimes the formatting makes the code harder to read. e.g. when it puts a long array inizalisation into a single line. In that case I don't want him to format it, but rather leave it ofer multiple lines.
E.g.
define([
'jquery',
'aloha',
'aloha/plugin',
'ui/ui',
'ui/scopes',
'ui/button',
'ui/toggleButton',
'ui/port-helper-attribute-field',
'ui/text'
// 'css!youtube/css/youtube.css'
],
function(
$,
Aloha,
Plugin,
Ui,
Scopes,
Button,
ToggleButton,
AttributeField)
{
this array should stay like this and don't become this:
define(['jquery', 'aloha', 'aloha/plugin', 'ui/ui', 'ui/scopes', 'ui/button', 'ui/toggleButton', 'ui/port-helper-attribute-field', 'ui/text' ], function($, Aloha, Plugin, Ui, Scopes, Button, ToggleButton, AttributeField) {
Is there a special tag, to tell eclipse not to format the code?
OK, it took me some time to find the right setting so I will post a toturial here.
Go to Window Preferences and Search the Formatter you are using. In my case it was under 'Aptana Studia' -> 'Formatter'. (Depending on your Package this differs, e.g. the Java Formatter is under 'Java' -> 'Code Style' -> 'Formater').
Noww create a new Build profile since you can't override the old one.
Now enable the Formatter tags.
Now you can use the
- #formatter:on
- #formatter:off
tags to disable code formatting.
Example:
this code:
function hello() { return 'hello';
}
//#formatter:off
/*
|\ _,,,---,,_
/,`.-'`' -. ;-;;,_
|,4- ) )-,_..;\ ( `'-'
'---''(_/--' `-'\_) fL
*/
//#formatter:on
function
world() {
return 'world';
}
Will get formatted to like this
function hello() {
return 'hello';
}
//#formatter:off
/*
|\ _,,,---,,_
/,`.-'`' -. ;-;;,_
|,4- ) )-,_..;\ ( `'-'
'---''(_/--' `-'\_) fL
*/
//#formatter:on
function world() {
return 'world';
}
Note how the function definition is formatted correct, while the ascii art isn't
Credits:
Katja Christiansen for his comment
https://stackoverflow.com/a/3353765/639035 : for a similar answer
Try to make an empty comment after each line:
define([ //
'jquery', //
'aloha', //
'aloha/plugin', //
'ui/ui', //
'ui/scopes', //
'ui/button', //
'ui/toggleButton', //
...
Not nice, but I think it will work.