From bf8c2c8cdcec31baeff1b55330d52fe1b60ae135 Mon Sep 17 00:00:00 2001 From: "Alex A. Naanou" Date: Fri, 6 Nov 2020 17:25:25 +0300 Subject: [PATCH] addes stoppable iterator functions to Array... Signed-off-by: Alex A. Naanou --- Array.js | 25 +++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Array.js b/Array.js index f0ede2a..3a4c3c8 100644 --- a/Array.js +++ b/Array.js @@ -187,6 +187,30 @@ Array.prototype.inplaceSortAs = function(other){ return this } +// Equivalent to .map(..) / .filter(..) / .reduce(..) / .. with support for +// StopIteration... +// +// NOTE: these add almost no overhead to the iteration. +// +// XXX should these return a partial result on StopIteration? +var wrapIterFunc = function(iter){ + return function(func){ + try { + return this[iter](...arguments) + // handle StopIteration... + } catch(err){ + if(err === StopIteration){ + return + } else if( err instanceof StopIteration){ + return err.msg } + throw err } } } + +Array.prototype.smap = wrapIterFunc('map') +Array.prototype.sfilter = wrapIterFunc('filter') +Array.prototype.sreduce = wrapIterFunc('reduce') +Array.prototype.sforEach = wrapIterFunc('forEach') + + // Equivalent to .map(..) / .filter(..) / .reduce(..) that process the // contents in chunks asynchronously... // @@ -225,6 +249,7 @@ Array.prototype.inplaceSortAs = function(other){ // The main goal of this is to not block the runtime while processing a // very long array by interrupting the processing with a timeout... // +// XXX should these return a partial result on StopIteration? var makeChunkIter = function(iter, wrapper){ wrapper = wrapper || function(res, func, array, e){ diff --git a/package.json b/package.json index 4b365d9..65d1cb7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ig-types", - "version": "3.1.0", + "version": "3.2.0", "description": "Generic JavaScript types and type extensions...", "main": "main.js", "scripts": {