You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Often it makes sense for a protocol to have optional fields that can be omitted entirely (but considered when they're used) but still included conceptually as part of the protocol.
For example:
protocolHash{hash;// Not optional// Hashing might be expensive so objects can report they can be cached// if they want
?cacheable;// Optional, syntax not important}consthashes=newWeakMap()functionhash(value){if(hashes.has(value)){returnvalue}if(!(valueimplementsHash)){thrownewError(`Can't hash ${value}`)}consthash_=value[Hash.hash]()if(value[Hash.cacheable]&&value[Hash.cacheable]()){hashes.set(value,hash_)}returnhash_}classHashTable{ ... }classPointimplementsHash{constructor(x,y){this.x=xthis.y=y}[Hash.hash](){returnthis.x+this.y}[Hash.cacheable](){returntrue}}classTupleimplementsHash{constructor(...args){this._tuple=args}[Hash.hash](){returnthis._tuple.reduce((acc,hash)=>acc+hash,0)}// As immutable can cache[Hash.cacheable](){returntrue}}Array.prototype[Hash.hash]=function(){returnthis.reduce((acc,hash)=>acc+hash,0)}// Hash.cacheable needn't be implemented as Array is mutableReflect.implement(Array.prototype,Hash)
Obviously this is a trivial example but with more complex protocols this would see better benefit.
For example if Iterator were a protocol:
protocolIterator{'next';// Not optional
?'return';// Optional
?'throw';// Optional}
The text was updated successfully, but these errors were encountered:
Often it makes sense for a protocol to have optional fields that can be omitted entirely (but considered when they're used) but still included conceptually as part of the protocol.
For example:
Obviously this is a trivial example but with more complex protocols this would see better benefit.
For example if Iterator were a protocol:
The text was updated successfully, but these errors were encountered: