Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

generator-foreach

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

generator-foreach

forEach for generators

  • 0.1.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
10
decreased by-74.36%
Maintainers
1
Weekly downloads
 
Created
Source

generator-foreach

forEach for generators

Imagine you want to use forEach inside a generator function:


var stuff = [1, 2, 3, 4, 5]

function * fn () {
  stuff.forEach(something)

  function something (item) {
    console.log(item)
  }
}

for (var i of fn());

It works ok, but what if you want to yield a value based on an item?


var stuff = [1, 2, 3, 4, 5]

function * fn () {
  stuff.forEach(something)

  function something (item) {
    yield item
  }
}

for (var i of fn()) console.log(i)

Doesn't work anymore! You can't use yield inside an ordinary function. So generator-foreach comes into play:


var foreach = require('generator-foreach')
var stuff = [1, 2, 3, 4, 5]

function * fn () {
  yield * foreach(stuff, something)

  function * something (item) {
    yield item
  }
}

for (var i of fn()) console.log(i)

Do use it you need to remember a couple of things:

  • pass an array as a first argument;
  • use yield * before foreach;
  • make your iterator generator function.

Examples

Basic

Use --harmony or --harmony-generators --harmony-iteration flags

/**
 * basic example
 */

var foreach = require('generator-foreach')

function * gen (array) {
  yield * foreach(array, function * (num) {
    yield num + 1
  })
}


for (var num of gen([1, 2, 3])) console.log(num)

Fancy recursive array flattening

Use --harmony or --harmony-generators --harmony-iteration flags

/**
 * fancy recursive array flattening
 */

var foreach = require('generator-foreach')

function * value (val) {
  yield val
}

function * flatten (array) {
  yield * Array.isArray(array) ? foreach(array, flatten) : value(array)
}

var array = [1, 2, [3, [4, 5, [6, 7]]]]

for (var num of flatten(array)) console.log(num)

FAQs

Package last updated on 09 Feb 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc