search

Pythonizing JavaScript

Python has many powerful utility functions such as range, enumerate, zip, etc., which are built on iterable objects and the iterator protocol. Combined with generator functions, these protocols have been available in all Evergreen browsers and Node.js since around 2016, but their usage is surprisingly low, in my opinion. In this article, I’ll implement some of these helper functions using TypeScript in hopes of changing that.

Iterators, iterables and generator functions

Iterator protocol

The iterator protocol is a standard way to generate a sequence of values. For an object to be an iterator, it must adhere to the iterator protocol by implementing the next method, for example:

const iterator = {
  i: 0,
  next() {
    return { done: false, value: this.i++ };
  }
};

We can then call the next method repeatedly to get the value:

console.log(iterator.next().value); // → 0
console.log(iterator.next().value); // → 1
console.log(iterator.next().value); // → 2
console.log(iterator.next().value); // → 3
console.log(iterator.next().value); // → 4
The

next method should return an object containing a value property (containing the actual value) and a done property (specifying whether the iterator has been exhausted, i.e. whether it can no longer produce values). According to MDN, neither attribute is strictly required and if both are missing, the return value is treated as { done: false, value: undefined }.

Iterable object protocol

The Iterable Object protocol allows an object to define its own iteration behavior. To adhere to the Iterable Object protocol, an object must define a method using the Symbol.iterator key that returns an iterator. Many built-in objects such as Array, TypedArray, Set and Map implement this protocol so they can be iterated using a for...of loop.

For example, for an array, the values method is specified as the Symbol.iterator method of the array:

console.log(Array.prototype.values === Array.prototype[Symbol.iterator]); // → true

We can combine the iterator and iterable object protocols to create an iterable iterator as follows:

const iterable = {
  i: 0,
  [Symbol.iterator]() {
    const iterable = this;
    return {
      next() {
        return { done: false, value: iterable.i++ };
      }
    };
  }
};

The names of these two protocols are unfortunately very similar and still confuse me to this day.

As you might have guessed, our iterator and iterable object examples are infinite, meaning they can generate values ​​forever. This is a very powerful feature, but it can also easily become a trap. For example, if we were to use an iterable in a for...of loop, the loop would continue forever; or as a parameter to a Array.from, JS would eventually throw a RangeError because the array would become too large :

// 将无限循环:
for (const value of iterable) {
  console.log(value);
}

// 将抛出 RangeError
const arr = Array.from(iterable);

The reason iterators and iterables can even go infinite is that they are lazily evaluated, i.e. they only produce a value when used.

Generator function

While iterators and iterable objects are valuable tools, they can be a bit cumbersome to write. As an alternative, generator functions were introduced.

Generator functions are specified using function* (or function *, the asterisk can be anywhere between the function keyword and the function name), allowing us to interrupt the execution of the function and return a value using the yield keyword , and resume execution where it left off later, while maintaining its internal state:

const iterator = {
  i: 0,
  next() {
    return { done: false, value: this.i++ };
  }
};

Python Utilities

As mentioned in the introduction, Python has some very useful built-in utilities based on the above protocol. JavaScript has also recently added some helper methods for iterators, such as .drop() and .filter(), but (maybe not yet) has some of the more interesting utilities in Python.

Let’s get hands-on!

Now that the theory part is over, let’s start implementing some Python functions!

Note: None of these implementations shown here should be used as-is in production environments. They lack error handling and boundary condition checking.

enumerate(iterable [,start])

enumerate in Python returns a sequence of tuples for each item in an input sequence or iterable, where the first position contains the count and the second position contains the item:

console.log(iterator.next().value); // → 0
console.log(iterator.next().value); // → 1
console.log(iterator.next().value); // → 2
console.log(iterator.next().value); // → 3
console.log(iterator.next().value); // → 4

enumerate also accepts an optional start parameter indicating where the counter should start:

console.log(Array.prototype.values === Array.prototype[Symbol.iterator]); // → true

Let’s implement this in TypeScript using generator functions. We can use the implementation outlined in the python documentation as a guide

const iterable = {
  i: 0,
  [Symbol.iterator]() {
    const iterable = this;
    return {
      next() {
        return { done: false, value: iterable.i++ };
      }
    };
  }
};

Since strings in JavaScript implement the Iterable Object protocol, we can simply pass the string to our enumerate function and call it like this:

// 将无限循环:
for (const value of iterable) {
  console.log(value);
}

// 将抛出 RangeError
const arr = Array.from(iterable);

repeat(elem [,n])

repeat is part of the built-in itertools library, which repeats the given input elem n times, or infinitely if n is not specified. Once again we can use the implementation in the python documentation as a starting point.

function* sequence() {
  let i = 0;
  while (true) {
    yield i++;
  }
}

const seq = sequence();
console.log(seq.next().value); // → 0;
console.log(seq.next().value); // → 1;
console.log(seq.next().value); // → 2;

// 将无限循环,从 3 开始
for (const value of seq) {
  console.log(value);
}

(The implementation of the cycle and range functions is omitted here because it is too long, but the logic is the same as the original text, just the code is rewritten in TypeScript)

Conclusion

This is my first blog post, I hope you find it interesting and maybe you will use iterators, iterables, and generators in future projects. If you have any questions or need clarification please leave a comment and I'll be happy to provide more information.

One thing to note is that the performance is nowhere near the original for loop using a counter. This may not matter in many cases, but it definitely matters in high-performance scenarios. It bothers me to find that frames are being lost when I draw PCM data to a canvas and use iterators and generators. This may be obvious in hindsight, but it wasn't to me at the time :D

Cheers!

The above is the detailed content of Pythonizing JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools