CoffeeScript: Create a shallow copy of an object and rename/drop properties with a one-liner - coffeescript

Given:
externalObject = {
UglyKeyOne: 'val1'
UglyKeyTwo: 'val2'
UglyUnusedKey: 'boo'
}
Is there a way to do the below 2 lines, in a one liner? i.e. to create newObject, and use the destructuring assignment in one step?
{ UglyKeyOne: keyOne, UglyKeyTwo: keyTwo } = externalObject
newObject = { keyOne, keyTwo }

This works:
newObject = { keyOne, keyTwo } = { keyOne: externalObject.UglyKeyOne, keyTwo: externalObject.UglyKeyTwo }

Related

Fusion (Typoscript 2): How to access a variable from a parent object?

This is sort of a follow-up question for How to define and access local variable in Typoscript 2 (Neos)?
If I define a local variable, called myLocalVar in the example below, how can I access it from other objects, in this case from Neos.Fusion:Case?
prototype(Some.Namespace:SomeNodeType) < prototype(TYPO3.Neos:Content) {
myLocalVar = ${String.split(q(node).property('example'), '/', 2)}
myResult = Neos.Fusion:Case {
a = Neos.Fusion:Matcher {
condition = ${???.myLocalVar[0] == 'aaa'}
renderer = 'first part is aaa'
}
b = Neos.Fusion:Matcher {
condition = ${???.myLocalVar[0] == 'bbb'}
renderer = 'first part is bbb'
}
}
}
In this concrete example: How can I access myLocalVar from inside Neos.Fusion:Matcher?
The part in question is the condition: condition = ${???.myLocalVar[0] == 'aaa'}
You need to define your myLocalVar as context variable:
#context.myLocalVar = ${String.split(q(node).property('example'), '/', 2)}
the context is inherited by all nesting objects, so you can just access the value like this
a = Neos.Fusion:Matcher {
condition = ${myLocalVar[0] == 'aaa'}
renderer = 'first part is aaa'
}

Calling instance method on each object in array

Let's assume this situation: I have an array of objects and I want call instance method on each one of them. I can do something like that:
//items is an array of objects with instanceMethod() available
items.forEach { $0.instanceMethod() }
The same situation is with map. For example I want to map each object to something else with mappingInstanceMethod which returns value:
let mappedItems = items.map { $0.mappingInstanceMethod() }
Is there a cleaner way to do that?
For example in Java one can do:
items.forEach(Item::instanceMethod);
instead of
items.forEach((item) -> { item.instanceMethod(); });
Is similiar syntax available in Swift?
What you are doing in
items.forEach { $0.instanceMethod() }
let mappedItems = items.map { $0.mappingInstanceMethod() }
is a clean and Swifty way. As explained in Is there a way to reference instance function when calling SequenceType.forEach?, the first statement cannot be reduced
to
items.forEach(Item.instanceMethod)
There is one exception though: It works with init methods
which take a single argument. Example:
let ints = [1, 2, 3]
let strings = ints.map(String.init)
print(strings) // ["1", "2", "3"]
for item in items {
item.instanceMethod()
}
have you tried
let mappedItems = items.map { $0.mappingInstanceMethod() }
note the () to call the method
Edit 1:
sample code:
class SomeObject {
func someFunction() -> Int {
return 5
}
}
let array = [SomeObject(), SomeObject(), SomeObject()]
let ints = array.map { $0.someFunction()}
print(ints)

Swift filter array of objects

class book{
var nameOfBook: String!
}
var englishBooks=[book(),book(),book()]
var arr = englishBooks.filter {
contains($0.nameOfBook, "rt")
}
I'm using this filter but with error cannot invoke filter with an argument
contains() checks if a sequence contains a given element, e.g.
if a String contains a given Character.
If your intention is to find all books where the name contains the substring "rt", then you can use rangeOfString():
var arr = englishBooks.filter {
$0.nameOfBook.rangeOfString("rt") != nil
}
or for case-insensitive comparison:
var arr = englishBooks.filter {
$0.nameOfBook.rangeOfString("rt", options: .CaseInsensitiveSearch) != nil
}
As of Swift 2, you can use
nameOfBook.containsString("rt") // or
nameOfBook.localizedCaseInsensitiveContainsString("rt")
and in Swift 3 this is
nameOfBook.contains("rt") // or
nameOfBook.localizedStandardContains("rt") // or
nameOfBook.range(of: "rt", options: .caseInsensitive) != nil
Sorry this is an old thread. Change you code slightly to properly init your variable 'nameOfBook'.
class book{
var nameOfBook: String!
init(name: String) {
nameOfBook = name
}
}
Then we can create an array of books.
var englishBooks = [book(name: "Big Nose"), book(name: "English Future
Prime Minister"), book(name: "Phenomenon")]
The array's 'filter' function takes one argument and some logics, 'contains' function can take a simplest form of a string you are searching for.
let list1 = englishBooks.filter { (name) -> Bool in
name.contains("English")
}
You can then print out list1 like so:
let list2 = arr1.map({ (book) -> String in
return book.nameOfBook
})
print(list2)
// print ["English Future Prime Minister"]
Above two snippets can be written short hand like so:
let list3 = englishBooks.filter{ ($0.nameOfBook.contains("English")) }
print(list3.map({"\($0.nameOfBook!)"}))
SWIFT 4.0
In order to filter objects and get resultant array you can use this
self.resultArray = self.upcomingAuctions.filter {
$0.auctionStatus == "waiting"
}
in case you want to delete an interval of object which has specific IDs (matchIDsToDelete) from an array of object (matches)
var matches = [Match]
var matchIDsToDelete = [String]
matches = matches.filter { !matchIDsToDelete.contains($0.matchID) }
2020 | SWIFT 5.1:
short answer:
books.filter { $0.alias.range(of: filterStr, options: .caseInsensitive) != nil }
long sample:
public filterStr = ""
public var books: [Book] = []
public var booksFiltered: [Book] {
get {
(filterStr.isEmpty )
? books
: books.filter { $0.alias.range(of: filterStr, options: .caseInsensitive) != nil }
}
}
I think this is more useful for lack of wrong typing situation.
englishBooks.filter( { $0.nameOfBook.range(of: searchText, options: .caseInsensitive) != nil}
In Swift 4.2 use the remove(where:) functionality. filter isn't doing well with memory, remove(where:) does the job better.
To do what you want:
englishBooks.removeAll { !$0.nameOfBook.contains("English") }

Perl map to map [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I create a hash of hashes in Perl?
I need to create something which is an equivalent of map : name(string) to map date(string/int) to value, i.e. a map { string => map { string => value } } .
How should i go about it in perl ?
The following code does not work.
my %strtomap_;
# given $str_, $date_, $val_
if ( ! exists $strtomap_ { $str_ } )
{
my %new_map_date_to_val_ ;
$new_map_date_to_val_{$date_} = $val_;
$strtomap_ { $str_ } = %new_map_date_to_val_ ;
}
else
{
$strtomap_ { $str_ } { $date_ } = $val_;
}
Values of aggregate types (hashes and arrays) can only be scalars, not other aggregate types. So if you are going to explicitly use something like your %new_map_date_to_val_, you need to store a reference to it instead:
my %new_map_date_to_val;
$new_map_date_to_val_ { $date_ } = $val_;
$strtomap_ { $str_ } = \%new_map_date_to_val_;
though you can use an anonymous hash instead:
$strtomap_ { $str_ } = { $date_ => $val _ };
And in fact, the whole exists test is not needed, since simply dereferencing an undefined value in this kind of way will autovivify a hash reference for you. Your whole code can just be:
my %strtomap_;
$strtomap_ { $str_ } { $date_ } = $val_;

How to compare self.title to a string in Objective C?

What am I doing wrong in the below code? My if statement is missing something:
if ([self.title] = "Upcoming Events") {
} else {
}
Correct would be:
if( [self.title isEqualToString:#"Upcoming Events"] )
self.title is a pointer, you can only compare it to other pointers using == not their values.
if ([self.title isEqualToString:#"Upcoming Events"]) {
NSLog(#"True");
} else {
NSLog(#"False");
}
You just have to write like this:
if([self.title isEqualToString:#"Upcoming Events"])
{
}
else
{
}
also .... in a if you should use "==" instead of "=". When there is "==" it is checking if they are equal while if there is "=" it gives the first one the value of the second.