Symbol.iterator in Ripple codebase.
In this article, we review Symbol.iterator in Ripple codebase. We will look at:
-
What is Symbol.iterator?
-
Symbol.iterator in Ripple codebase.
What is Symbol.iterator?
The Symbol.iterator
static data property represents the well-known symbol Symbol.iterator
. The iterable protocol looks up this symbol for the method that returns the iterator for an object. In order for an object to be iterable, it must have an [Symbol.iterator]
key. — Mdn docs
Example
const iterable = {};
iterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
console.log([...iterable]);
// Expected output: Array [1, 2, 3]
Whenever an object needs to be iterated (such as at the beginning of a for...of
loop), its [Symbol.iterator]()
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
Some built-in types have a default iteration behavior, while other types (such as Object
) do not. Some built-in types with a [Symbol.iterator]()
method are:
Symbol.iterator in Ripple codebase
At L4 in packages/ripple/src/runtime/array.js, you will find the following code:
var symbol_iterator = Symbol.iterator;
and this is one of items in the array:
const introspect_methods = [
'entries',
'every',
...
'toLocaleString',
...
'toString',
symbol_iterator,
'values',
'with',
];
and this introspect_methods is called in init function as shown below:
#init() {
var proto = RippleArray.prototype;
var array_proto = Array.prototype;
for (const method of introspect_methods) {
proto[method] = function (...v) {
this.$length;
get_all_elements(this);
return array_proto[method].apply(this, v);
};
}
}
About me:
Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.
Email: ramu.narasinga@gmail.com
Want to learn from open-source? Solve challenges inspired by open-source projects.
References:
-
https://github.com/trueadm/ripple/blob/main/packages/ripple/src/runtime/array.js#L4
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator
-
https://github.com/trueadm/ripple/blob/main/packages/ripple/src/runtime/array.js#L31