Coffeescript help to simplify if clause - coffeescript

I have this part of code in Coffee Script, and i can't figure out how it could be simplified with ternary if or something like this..
if options.tracks?
#collection.add(options.tracks, {at: length+1, dest:options.dest})
else
#collection.add(options, {at: length+1, dest:options.dest})
Sorry for stupid question..

CoffeeScript has no easy tenary operator but you can use the if which will yield the last expression of either branch
#collection.add((if options.tracks then options.tracks else options),
{at: length+1, dest:options.dest})
Having said that. I wouldnt write it that way because imo its to much visual noise and hard to read. better do
tracks = if options.tracks then options.tracks else options
#collection.add(tracks, {at: length+1, dest:options.dest})
or even better
tracks = options.tracks || options
#collection.add(tracks, {at: length+1, dest:options.dest})

Using the existential operator will yield the same behaviour as you code:
#collection.add(options.tracks ? options, {at: length + 1, dest: options.dest})
I'd personally get rid of some the parens/braces and maybe use a separate variable for the first paramter... but this is more about personal preference really:
tracks = options.tracks ? options
#collection.add tracks, at: length + 1, dest: options.dest

Related

How can I manipulate a string in dart?

Currently I'm working in a project with flutter, but I realize there is a need in the management of the variables I'm using.
Basically I want to delete the last character of a string I'm concatenating, something like this:
string varString = 'My text'
And with the help of some method or function, the result I get:
'My tex'
Am I clear about it? I'm looking for some way which helps me to 'pop' the last character of a text (like pop function in javascript)
Is there something like that? I search in the Dart docs, but I didn't find anything about it.
Thank you in advance.
You can take a substring, like this:
string.substring(0, string.length - 1)
If you need the last character before popping, you can do this:
string[string.length - 1]
Strings in dart are immutable, so the only way to do the operation you are describing is by constructing a new instance of a string, as described above.
var str = 'My text';
var newStr = (str.split('')..removeLast()).join();
print(newStr);
Another way:
var newStr2 = str.replaceFirst(RegExp(r'.$') , '');
print(newStr2);

How to select symbols onWorkspaceSymbol

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.

Lazy filter for one element

I'm refactoring some scala code to teach my coworkers about for-comprehensions, and I've got a line like:
for {
// ...
result <- components.collectFirst({ case section if section.startsWith(DESIRED_SUBSTRING) => section.substring(section.indexOf(DELIM) + 1).trim() == "true" })
} yield result
That's a bit long.
At first, I wished I could just skip the result <- ... followed by the immediate yield, as I can in Haskell, but then I noticed the processing going on inside collectFirst.
So I thought it'd be much easier to read as I should better do this as
for {
// ...
section <- components.filter(_.startsWith(DESIRED_SUBSTRING)).headOption
} yield section.substring(section.indexOf(DELIM) + 1).trim() == "true"
Which works, but it is less efficient, since filter has to process all the elements. I'd like to be able to use a lazy filter:
components.withFilter(_.startsWith(DESIRED_SUBSTRING)).headOption
But FilterMonadic doesn't seem to support headOption, and I can't figure out a way to derive it from the operations it does support. I'm sure there's a way with flatMap and some bf, but I'm too unfamiliar with the scala ecosystem at the moment.
If I want to stick with standard library tricks, am I stuck with
for {
// ...
section <- components.collectFirst({ case section if section.startsWith(DESIRED_SUBSTRING) => section })
} yield section.substring(section.indexOf(DELIM) + 1).trim() == "true"
Or is there something better I can use?
If you use components.find(_.startsWith(DESIRED_SUBSTRING)) that will give you an Option with the first element that meets the condition. Then, you can just map over it with any subsequent processing you need.

Most concise way to assign value from hash only if it exists?

I find myself often writing code like this:
if ($optionalParamsRef->{verbosity}) {
$settingsHash{verbosity} = $optionalParamsRef->{verbosity};
}
However, it seems very verbose to repeat $optionalParamsRef->{verbosity} twice. Is there a shorter way?
Edit: Yes, I realize this is checking for true/false and not 'exists'. What I'm looking for is a concise functional equivalent to this.
Note you are checking $optionalParamsRef->{verbosity} for true, not exist.
Possible way to do this:
foreach my $k (qw/verbosity param1 param2 param3/) { #Enumerate keys here
$settingsHash{$k} = $optionalParamsRef->{$k} if exists($optionalParamsRef->{$k});
}
As others mentioned, your code checks for false-ness. If you considered false values as non-existant, you could have used the logical or. Probably this is not what you want.
$settingsHash{verbosity} = $optionalParamsRef->{verbosity} || $default;
But maybe defined-ness is enough. It's still no check for existence, but if your hash doesn't contain undef values, this could be enough:
$settingsHash{verbosity} = $optionalParamsRef->{verbosity} // $default;
using the "new" defined-or operator // instead of the logical or ||. I know these examples are not equivalent to the code you posted because they alwas assign something, but in my experience, this is often useful, so maybe it could help.
my $v = $optionalParamsRef->{verbosity};
$settingsHash{verbosity} = $v if $v;
for ($optionalParamsRef->{verbosity}) {
$settingsHash{verbosity} = $_ if $_;
}
A concise functional equivalent:
sub {$_[0]=$_[1] if $_[1]}->($settingsHash{verbosity}, $optionalParamsRef->{verbosity});
However, IMO, the main problem with your code is that you are only conditionally setting $settingsHash{verbosity}, keeping you from doing something simpler like:
$settingsHash{verbosity} = $optionalParamsRef->{verbosity} || somedefault
or even:
%settingsHash = ( %defaultSettings, %$optionalParamsRef );

sort json facebook data

i'm trying to figure out how to sort the json data provided by a facebook events feed.
This is the code I've been using
$int_count = 1;
$FBpage = file_get_contents('https://graph.facebook.com/demo/events?access_token=170978966368624|vNXbO1MPwpvP56jU6zWGCyRESQ');
$FBdata = json_decode($FBpage);
foreach ($FBdata->data as $events )
{
$x_sdt = explode("T",$events->start_time);
$x_sd = explode("-",$x_sdt[0]);
if($x_sdt[0] > date("Y-m-d"))
{
$StatusID = explode("_", $events->id);
echo '<ul class="shows">';
echo '<li class="date">';
echo $x_sd[2]."/".$x_sd[1]."/".$x_sd[0];
echo '</li>';
echo '<li class="title">'.maxTruncate($events->name, 62).'</li>';
echo '</ul>';
}
$int_count++;
if($int_count==5){ break; }
}
Can anyone point me in the right direction, so far I beleive i should be using usort(), but when I look at tutorials i've got no idea what the go is. any bombs of wisdom would be greatly appreciated.
Thanks
Frank
With usort, you just have to write your own little comparison function, that gets two of the arrays elements as parameters, compares them by whatever metric you like, and returns a value saying which one is supposed to be considered “greater” than the other.
Have a look at the examples in the PHP manual, it’s really quite easy.
If you still can’t get it to work on your own, then please describe what you tried and on what (example) data structure.