惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero
博客园 - 叶小钗
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
I
InfoQ
F
Fortinet All Blogs
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
T
Tenable Blog
B
Blog RSS Feed

Minko Gechev's blog

skillgrade Unit Tests for AI Agent Skills You Should Care About AI Generative Development LLM-first Web Framework Reactive framework in ~200 lines of JavaScript Managing Angular Are LLMs going to replace us? Prefetching Heuristics Design Patterns in Open Source Projects - Part II Design Patterns in Open Source Projects - Part I What I learned doing 125 public talks - Part I Dynamic imports solve all the problems, right? 5 Angular CLI Features You Didn't Know About Angular quicklink Preloading Strategy Introducing Bazel Schematics for Angular CLI Building TypeScript Projects with Bazel Joining Google Playing Mortal Kombat with TensorFlow.js. Transfer learning and data augmentation Fast, extensible, configurable, and beautiful linter for Go Introducing Guess.js - a toolkit for enabling data-driven user-experiences on the Web Machine Learning-Driven Bundling. The Future of JavaScript Tooling. JavaScript Decorators for Declarative and Readable Code 3 Tricks For Using Redux and Immutable.js with TypeScript Follow Your Dream Career with Open Source. Personal Story. Redux Anti-Patterns - Part 1. State Management. Faster Angular Applications - Understanding Differs. Developing a Custom IterableDiffer Faster Angular Applications - Part 2. Pure Pipes, Pure Functions and Memoization Faster Angular Applications - Part 1. On Push Change Detection and Immutability Understanding Dynamic Scoping and TemplateRef Implementing a Simple Compiler on 25 Lines of JavaScript Developing Statically Typed Programming Language WebVR for a Gamified IDE 7 Angular Tools That You Should Consider Announcing ngrev - Reverse Engineering Tool for Angular Implementing Angular's Dependency Injection in React. Understanding Element Injectors. Distributing an Angular Library - The Brief Guide Angular in Production Ahead-of-Time Compilation in Angular 2.5X Smaller Angular 2 Applications with Google Closure Compiler Using Stripe with Angular (Deprecated) Building an Angular Application for Production Implementing the Missing "resolve" Feature of the Angular 2 Router Scalable Single-Page Application Architecture Managing ambient type definitions and dealing with the "Duplicate identifier" TypeScript error Static Code Analysis of Angular 2 and TypeScript Projects Enforcing Best Practices with Static Code Analysis of Angular 2 Projects ViewChildren and ContentChildren in Angular Dynamically Configuring the Angular's Router Angular 2 Hot Loader Lazy Loading of Route Components in Angular 2 Aspect-Oriented Programming in JavaScript Flux in Depth. Store and Network Communication. Using JSX with TypeScript Flux in Depth. Overview and Components. Even Faster AngularJS Data Structures Boost the Performance of an AngularJS Application Using Immutable Data - Part 2 Angular2 - First Impressions Build Your own Simplified AngularJS in 200 Lines of JavaScript Persistent State of ReactJS Component Boost the Performance of an AngularJS Application Using Immutable Data Processing Binary Protocols with Client-Side JavaScript Stream your Desktop to HTML5 Video Element Multi-User Video Conference with WebRTC Asynchronous calls with ES6 generators WebRTC chat with React.js AngularJS in Patterns (Part 3) AngularJS in Patterns (Part 2). Services. Using GitHub Pages with Jekyll! AngularJS in Patterns (Part 1). Overview of AngularJS Singleton in JavaScript Express over HTTPS What I get from the JavaScript MV* frameworks Remote Desktop Client with AngularJS and Yeoman The magic of $resource (or simply a client-side Active Record) AngularJS Inheritance Patterns AngularAOP v0.1.0 Advanced JavaScript at Sofia University AngularJS style guide Lazy prefetching of AngularJS partials VNC client on 200 lines of JavaScript Aspect-Oriented Programming with AngularJS CSS3 flipping effect Practical programming with JavaScript Why I should use publish/subscribe in JavaScript JavaScript, the weird parts Functional programming with JavaScript plainvm Looking for performance? Probably you should NOT use [].sort (V8) JavaScript image scaling ELang Caching CSS with localStorage Self-invoking functions in JavaScript (or Immediately Invoked Function Expressions) Asus N56VZ + Ubuntu 12.04 (en) Asus N56VZ + Ubuntu 12.04 Debian Squeeze + LXDE on Google Nexus S (or having some fun while suffering) HTML5 image editor Курсови проекти – ФМИ Carousel Gallery SofiaJS...
Binary Tree iterator with ES6 generators
2014-09-13 · via Minko Gechev's blog

ES6 specification is being clarified every passed day! One of the key features of the new version of the language are the generators. Generators (a.k.a. semicoroutines) will play quite important role after they are being officially released. They could be used to simplify the asynchronous control flow of any JavaScript program (look at co). Another important role is using them for creating iterators.

In this blog post we are going to take a look at how could be implemented iterator of binary search tree using the ES6 generators.

Initially I’m going to tell a few words about how generators could be used, after that we will look at the iterator design patterns and last, but not least we are going to take a look at the BST (binary search tree) iterator implementation.

Getting started

ES6 generators

In JavaScript we can define generator by using the following syntax:

function* generator() {
  // body
}

Once we have defined given generator, we can instantiate it (more preciously we create an iterator) by simply invoking it like a function:

Ok, so far we know how to define generators and instantiate them. The interesting part comes when we include the keyword yield into the game. With yield we can suspend the execution of the current generator and change the control flow:

function* generator(param) {
  yield 42;
  var returnRes = yield param;
  return returnRes;
}

var gen = generator(3.1415926535);
gen.next(); // { value: 42, done: false }
gen.next(); // { value: 3.1415926535, done: false }
gen.next(1.618); // { value: 1.618, done: true }

Initially we create a new instance of the generator and pass Pi as parameter. Later with yield 42 we suspend the execution of the generator. By calling the next method we restore the execution from the last suspension point. By passing argument to next we can get value from the outside of the generator (like in var returnRes = yield param).

So far so good, but some times we want to pass the execution to another generator. For this case we have a special syntax - yield* generator(params):

function* foo() {
  console.log('In foo');
  var c = yield* bar(1.618);
  console.log(c);
}

function* bar(param) {
  console.log('In bar');
  yield param;
  return 42;
}

var f = foo();
f.next();
f.next();
/**
  // In foo
  // In bar
  // 42
*/

Iterator Design Pattern

The iterator pattern belongs to the behavioral design patterns. It is used with collections of objects and its main aim is separation of the logic for traversing given collection, from the actual collection’s implementation.

“Iterator”

Big advantage of this design pattern is that the abstract Iterator class provides common interface, which could be later implemented by multiple ConcreteIterators. This way we can traverse different collections (BSTs, linked lists, hash maps, etc.) using the same interface provided by the collection’s iterator.

Implementation

In this section we’ll take a look at the actual implementation of our BST iterator. Since the logic behind the data structure is not in the scope of this blog post, you can take a look at my repository - javascript-algorithms for additional details. In this article we are going to extend the BST’s API by adding a method called getIterator. Here is its implementation:

BinaryTree.prototype.getIterator = function () {
  return new BinarySearchTreeIterator(this).next(this._root);
};

In the snippet above, we create new instance of BinarySearchTreeIterator by passing the current BST instance and after that invoking it’s next method. The next method of the iterator will return the next element of the collection. Initially, during the creation of the iterator, we need to call it because the next method is actually a generator, so by invoking it we return new instance of the generator.

Here is the implementation of the iterator:

function BinarySearchTreeIterator(tree) {
  this._tree = tree;
}

BinarySearchTreeIterator.prototype.next = function* (current) {
  if (current === undefined)
    current = this._tree._root;
  if (current === null)
    return;
  yield* this.next(current._left);
  yield current.value;
  yield* this.next(current._right);
};

You can see that the only difference between the in-order traverse of the BST using iterator and the one implemented in the BST, is that the iterator uses yield. Different yield syntax is used depending on whether we want to suspend the execution or to “redirect” it to different generator instead.

Here is how our iterator could be used:

var tree = new BinaryTree();

tree.insert(5);
tree.insert(1);
tree.insert(6);
tree.insert(0);

var i = tree.iterator();
var current;
while (!(current = i.next()).done) {
  console.log(current.value);
}
// 0 1 5 6