Add JavaScript prototype methods with Symbols

jcbhmr1 pts0 comments

DocumentationDocumentation

Symbola is a proof-of-concept library for 🤯 extending the native JavaScript prototypes 🤯 with methods identified by symbols to prevent naming collisions, which enables method chaining syntax without having to wrap or convert the target. For example, Map and Set objects don't have built-in iteration methods, so iterating over them requires a conversion to an array:

const xs = new Set([1, 2, 3, 4])<br>// Converting to array with ... spread syntax to chain map and filter<br>const ys = [...xs].map((x) => x + 1).filter((x) => x % 2)<br>Copy

In comparison, extending the native prototypes allows to use iteration methods on iterables without conversion:

// Importing the unique symbols used to access iteration methods<br>import { map, filter } from '@symbola/iterable'

const xs = new Set([1, 2, 3, 4])<br>// Calling [map] and [filter] methods without conversion<br>const ys = xs[map]((x) => x + 1)[filter]((x) => x % 2)<br>Copy

⭐ Try Symbola in an interactive sandbox

📖 Article exploring symbol protocol extensions in more depth

Rationale for symbol protocol extensions<br>The key difference when extending native prototypes with symbols as keys is that symbol primitives are unique, so there is no practical chance of repeating situations like SmooshGate, where a non-standard Array.prototype.flatten method prevented a standard method with the same name from being added. The trade off is that accessing methods with symbols requires the [] operator instead of the ., but it's a small difference compared to overcoming the limitations of method chaining that are well documented in, for example, the pipeline operator proposal. In short, extending native prototoypes is a workaround for making fluent interfaces more widely applicable without the downsides of other workarounds like temporary variables or wrappers like _.chain.

Similar features in other languages<br>A number of other languages have ad-hoc extension features like trait composition or protocol extensions, which allow to retroactively extend types without modifying their definition based on conformity to a specific blueprint, contract, convention or protocol. For example, JavaScript defines iteration protocols, which are a set of requirements for types to be iterable, which means returning an associated iterator type when the [Symbol.iterator]() method is called, which in turn implements methods to return iteration results. Conforming to the iteration protocols means that the type is supported by for-of loop syntax or yield or yield* operators in generator functions, and is also supported by third-party utility libraries like IxJS or iterall, but these libraries have generally had limited adoption because of the limitations of chaining syntax in JavaScript, where retroactively extending types with chainable methods requires using wrappers, or to extend the native prototypes as in the iteration helpers proposal, which means going through an exceedingly long standardization process.

Symbol protocol extensions are a userland workaround for the typical limitations of avoiding a nested coding style in JavaScript, and it uses the language's flexibility to implement something similar to Rust traits, Swift protocols or Haskell typeclasses, and an additional advantage over, for example, the proposed standard extensions to native prototypes is that symbol protocols work for all objects that implement them, not just those inheriting from specific intrinsics like %Iterator.prototype%.

Type safety<br>TypeScript allows constraining methods to just receivers that conform to a specific protocol, so symbol protocol methods are typed to prevent being used with non-conforming types like so:

[filter]()A>(this: IterableA>, fn: (a: A) => boolean) { ... }<br>Copy

The actual implementation for the symbol protocols also does not rely on anything magical and just add the methods to the native prototypes and use declaration merging to make TypeScript recognize the added methods.

Full implementation for the filterable protocol<br>import { extend } from '@symbola/core'

export const filter = Symbol('filter')

export default abstract class Filterable {<br>*[filter]T>(this: IterableT>, callback: (value: T) => boolean) {<br>for (const value of this) {<br>if (callback(value)) {<br>yield value

declare global {<br>interface Object extends Filterable {}

extend(Object.prototype, Filterable.prototype)<br>Copy

Standard ad-hoc extension proposal<br>Aside from the |> pipeline operator proposal, there is also the :: bind operator proposal that addresses the same issue of ad-hoc extension of existing types, and there is also a stage-1 extensions proposal based on the same operator, which would essentially do the same as is currently already possible in userland with symbol protocol extensions.

Example use cases<br>Lazy iteration<br>The symbol methods are added to Object.prototype, so they work on any object that implements the JavaScript iteration protocols, including generators:

import { filter } from...

methods symbol filter iteration protocol native

Related Articles