Name for pattern T | Array<T> - javascript

A common pattern that libraries use is accepting a type or an array of that type as an argument to a function. For example:
interface JQuery {
add(selector: HTMLElement | HTMLElement[]): this;
}
Is there a name for this pattern? I'd like to alias it to improve readability. My first guess is TypeOrArray<T> but this sounds clunky and may potentially be unintuitive.
Note: I've tagged this typescript since that's what I'm using and something idiomatic may be a better answer. However, this should apply to any language that makes use of generics.

That syntax is typescript's way of allowing you to define multiple types for a single parameter.
In your case the selector can be either an HTMLElement or an Array of HTMLElement.
The same you can do for any type:
function example(parameter: number | string) {
}
example(5) // works
example('2') // works
example(new Date()) // fails

I don't think the pattern actually is "type or array of the type".
It's more like "whatever the author of the library considered to be convenient for its users".
Typescript union type fits pretty good here, it allows you to describe whatever combination of types is acceptable for particular function, without thinking too much about names.
If you inclined to name your types, the appropriate name could be
type HTMLElementsToAdd = HTMLElement | HTMLElement[];
The purpose is to indicate that the type is not just an element array, and is specific to add method. Cursory look through jQuery API docs confirms that it hardly follows any specific pattern, and actually uses "or" to describe acceptable types, for example:
.append( content [, content ] )
content
Type: htmlString or Element or Text or Array or jQuery

Related

How to convert a JavaScript Symbol to a string without the "Symbol(" prefix?

For example, if I use toString():
let s = Symbol('abc')
console.log(s.toString())
I get:
'Symbol(abc)'
How to get just the:
'abc'
part instead?
I know how to do this with string manipulation, but I would hope for a potentially more efficient solution that directly obtains the value.
I am using Symbol to implement an Enum: What is the preferred syntax for defining enums in JavaScript? and want to serialize it with a toJSON() on the containing class.
Tested in Node.js v10.15.1.
Use description to get value
s.description
As when we create Symbol we pass description of that symbol.
For more read this.
I would use s.description. It will return the description of the Symbol.
A deeper explanation here.

Use underscore to change one property of objects in an array

I'm hoping to take advantage of underscore to avoid writing for loops throughout my code base. I'm using map in place of a for loop like so:
body.tags = _.map(body.tags, function(tag) {
return {
id: tag.id,
userId: tag.userId,
createDate: tag.createDate,
tag: tag.tag.toLowerCase(),
};
});
My question is, is there a way to do this without specifying the properties that won't be changing (everything but tag)? It seems like overkill to specify fields like id: tag.id.
You don't even need underscore for this:
body.tags.forEach(function(t) { t.tag = t.tag.toLowerCase();});
map (whether native, underscore or others) is used to transform whole values, it's not a typical use case to do what you tried to do with it. Also, using a simple for might perform better since you don't need function calls here, but that depends on runtime optimizations.
By the way, if you replace the mapping function with the function from this answer and not set the return value back to body.tags, you'll also get your desired result.
You could try the following code to change a single property in a collection using underscore.
_.map(body.tags, function(tag) {
tag.tag = tag.tag.toLowerCase();
return tag;
});
There is one benefit in using lodash's map method (similar to underscore library) over native forEach and its performance. Based on why lodash is faster than native forEach post, maybe it's justifiable to use lodash in favour of both underscore and native forEach to loop. However I would agree with the user who commented below "Choose the approach that is most writable, readable, and maintainable".

chai things - comprehensive list of should() methods

I'm looking for a comprehensive list of methods you can call on a decorated object using the chai-things library for chai.js
so, for example :
myObject.should.METHOD_NAME.
What are all of the valid METHOD_NAMEs that can be called in the above statement. If valid method names are based on object type, is there a table listing methods per object type available ?
for example, here are some of the methods available:
an
change
changes
contain
contains
decrease
decreases
include
includes
increase
increases
length
not
be
eql
Here is another example, if you call 'increase' on an array assertion you get an error, whereas if you call 'contain' it's okay. I'm seeking the documentation that describes these rules.
thanks
All of the methods for should are available in the docs under "Expect / Should" (http://chaijs.com/api/bdd/), for example here's the docs for contain (which is an alias of .include):
.include(value)
#param{ Object | String | Number }obj
#param{ String }message_optional_
The include and contain assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the contains flag for the keys assertion.
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
The docs show examples using the expect(foo).to... syntax, but expect(foo).to. and foo.should are completely interchangeable.
If you want you can also look at the source code - all of the core assertions are in one file; chai/lib/core/assertions.js - they're constructed using addMethod but each one comes with docs (the docs are used to generate the website) so it should be easy enough to read.
Every method is available from .should - but there are some special "properties" to help form approximations of english sentences, they don't do anything but they can be used to chain an assertion - these are
to
be
been
is
that
which
and
has
have
with
at
of
same
(So if you really wanted to, you could write 'a'.should.to.be.been.is.that.which.and.has.have.with.at.of.same.equal('a') - and this would have the same effect as 'a'.should.equal('a'))

Is there a performance impact to using virtual getters in Mongoose with Node.js?

I'm starting to make use of virtual getter methods in Mongoose in a real-world application and am wondering if there is a performance impact to using them that would be good to know about up-front.
For example:
var User = new Schema({
name: {
first: String,
last: String
}
});
User.virtual('name.full').get(function () {
return this.name.first + ' ' + this.name.last;
});
Basically, I don't understand yet how the getters are generated into the Objects Mongoose uses, and whether the values are populated on object initialisation or on demand.
__defineGetter__ can be used to map a property to a method in Javascript but this does not appear to be used by Mongoose for virtual getters (based on a quick search of the code).
An alternative would be to populate each virtual path on initialisation, which would mean that for 100 users in the example above, the method to join the first and last names is called 100 times.
(I'm using a simplified example, the getters can be much more complex)
Inspecting the raw objects themselves (e.g. using console.dir) is a bit misleading because internal methods are used by Mongoose to handle translating objects to 'plain' objects or to JSON, which by default don't include the getters.
If anyone can shed light how this works, and whether lots of getters may become an issue at scale, I'd appreciate it.
They're probably done using the standard way:
Object.defineProperty(someInstance, propertyName, {get: yourGetter});
... meaning "not on initialization". Reading the virtual properties on initialization would defeat the point of virtual properties, I'd think.

javascript equivalent of union in c

I wonder if there is an equivalent of c/++ union in Javascript? I need to use it as a library I use for an Html5 game wants some fixed variable names for the object I pass to a function of this library however it is much easier for me to keep the data in an array for easier calculation.
To give an example, say there is a function 'F' in the library which takes a transformation matrix as a parameter. The parameter must have variable names 'a', 'b', ... 'f' which correspond to matrix elements(m[0][0], m[0][1] ...) consecutively. I have my own matrix class for calculations in which I use an array.
I know that entering the parameter 'on the fly', as shown below, sorts out my problem however I don't want to do that every time I call the function nor I want to write a proxy function.
F({a:m[0][0], b:m[0][1], c:[0][2], d:m[1][0], e:m[1][1], f:[1][2]});
is there any way around that such as union?
No, there's not.
There is no concept of a union, but since the language is loosely-typed you should never need anything of the sort.
You can change the type that is in a variable on the fly (and of course you can use an object with properties which are also loosely typed).

Categories

Resources