From 984dcd1c0fe8a83f83165294546108b87cebc302 Mon Sep 17 00:00:00 2001 From: Joel Denning Date: Sun, 7 Apr 2019 11:07:28 -0600 Subject: [PATCH] Making the registry iterable. See #1918. (#1919) --- docs/api.md | 16 ++++++++++++++++ src/features/registry.js | 23 ++++++++++++++++++++++- test/system-core.js | 21 +++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index ae5af7cfb..8282631d2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -87,3 +87,19 @@ System.set('http://site.com/normalized/module/name.js', { `module` is an object of names to set as the named exports. If `module` is an existing Module Namespace, it will be used by reference. + +#### System.entries() -> Array +Type: `Function` + +Allows you to retrieve all modules in the System registry. Each value will be an array with two values: a key and the module. Also available +at `System[Symbol.iterator]`. + +```js +System.entries().forEach((key, value) => { + console.log(entry); // ['http://localhost/path-to-file.js', {exportName: 'exportedValue'}] +}); + +for (let entry of System) { + console.log(entry); // ['http://localhost/path-to-file.js', {exportName: 'exportedValue'}] +} +``` \ No newline at end of file diff --git a/src/features/registry.js b/src/features/registry.js index aed89b63e..3f1aa3636 100644 --- a/src/features/registry.js +++ b/src/features/registry.js @@ -58,4 +58,25 @@ systemJSPrototype.delete = function (id) { depLoad.i.splice(importerIndex, 1); }); return delete this[REGISTRY][id]; -}; \ No newline at end of file +}; + +systemJSPrototype.entries = function () { + const registry = this[REGISTRY]; + return Object.keys(registry).map(function (key) { + return [key, registry[key].n]; + }); +} + +if (typeof Symbol !== 'undefined') { + systemJSPrototype[Symbol.iterator] = function () { + const registry = this[REGISTRY]; + const keys = Object.keys(registry); + let index = 0; + return { + next() { + const key = keys[index++]; + return { done: index > keys.length, value: key && [key, registry[key].n] }; + } + }; + } +} \ No newline at end of file diff --git a/test/system-core.js b/test/system-core.js index 6421e8787..59bf22d6c 100644 --- a/test/system-core.js +++ b/test/system-core.js @@ -137,6 +137,27 @@ describe('Core API', function () { assert(resolveReturnValue instanceof Promise); assert.equal(resolvedX, 'http://x'); }); + + it('Supports iteration', async function () { + loader.set('h', {a: 'b'}); + await loader.import('h'); + + let foundH = false; + for (let entry of loader) { + if (entry[0] === 'h' && entry[1].a === 'b') { + foundH = true; + } + } + + assert(foundH); + }); + + it('Supports System.entries', async function () { + loader.set('i', {a: 'b'}); + await loader.import('i'); + + assert(loader.entries().some(entry => entry[0] === 'i' && entry[1].a === 'b')); + }) }); });