├── cjs └── package.json ├── test ├── package.json ├── index.html └── index.js ├── .npmrc ├── .gitignore ├── es.js ├── types └── index.d.ts ├── .npmignore ├── rollup └── es.config.js ├── tsconfig.json ├── esm └── index.js ├── .github └── workflows │ └── node.js.yml ├── LICENSE ├── package.json └── README.md /cjs/package.json: -------------------------------------------------------------------------------- 1 | {"type":"commonjs"} -------------------------------------------------------------------------------- /test/package.json: -------------------------------------------------------------------------------- 1 | {"type":"commonjs"} -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | package-lock=true 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .nyc_output 3 | v8.log 4 | coverage/ 5 | node_modules/ 6 | cjs/* 7 | !cjs/package.json 8 | -------------------------------------------------------------------------------- /es.js: -------------------------------------------------------------------------------- 1 | self.a=(a=new WeakSet)=>function*(e){for(const o of e)a.has(o)||(a.add(o),yield o)};export{a as default}; 2 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | declare function _default(ws?: Set | WeakSet): (iterable: Iterable) => Generator; 2 | export default _default; 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .nyc_output 3 | .eslintrc.json 4 | .github/ 5 | .travis.yml 6 | v8.log 7 | coverage/ 8 | node_modules/ 9 | rollup/ 10 | test/ 11 | tsconfig.json 12 | -------------------------------------------------------------------------------- /rollup/es.config.js: -------------------------------------------------------------------------------- 1 | import {nodeResolve} from '@rollup/plugin-node-resolve'; 2 | import terser from '@rollup/plugin-terser'; 3 | 4 | 5 | export default { 6 | input: './esm/index.js', 7 | plugins: [ 8 | nodeResolve(), 9 | terser() 10 | ], 11 | 12 | output: { 13 | esModule: true, 14 | file: './es.js', 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "NodeNext", 4 | "target": "esnext", 5 | "moduleResolution": "nodenext", 6 | "allowJs": true, 7 | "declaration": true, 8 | "emitDeclarationOnly": true, 9 | "declarationDir": "types" 10 | }, 11 | "include": [ 12 | "esm/index.js", 13 | "esm/exports.js", 14 | "esm/xworker.js" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /esm/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Set | WeakSet} [ws] a `Set` or `WeakSet` (default) used to guard iterations. 3 | */ 4 | export default (ws = new WeakSet) => 5 | /** 6 | * @template T 7 | * @param {Iterable} iterable any iterable content. 8 | */ 9 | function* (iterable) { 10 | for (const any of iterable) { 11 | if (!ws.has(any)) { 12 | ws.add(any); 13 | yield any; 14 | } 15 | } 16 | } 17 | ; 18 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | loop-once 7 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | const loopOnce = require('../cjs'); 2 | 3 | const loop = loopOnce(); 4 | 5 | const iterable = [ 6 | Promise.resolve('a'), 7 | Promise.resolve('b'), 8 | Promise.resolve('c') 9 | ]; 10 | 11 | const result = []; 12 | 13 | const log = async () => { 14 | for (const p of loop(iterable)) 15 | result.push(await p); 16 | }; 17 | 18 | log(); 19 | log(); 20 | log(); 21 | log().then(log); 22 | log(); 23 | setTimeout(log, 500); 24 | setTimeout(() => { 25 | console.assert(result.join(',') === 'a,b,c'); 26 | console.log('OK'); 27 | }, 1000); 28 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: build 5 | 6 | on: [push, pull_request] 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [20] 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v2 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | cache: 'npm' 24 | - run: npm ci 25 | - run: npm run build --if-present 26 | - run: npm run coverage --if-present 27 | - name: Coveralls 28 | uses: coverallsapp/github-action@master 29 | with: 30 | github-token: ${{ secrets.GITHUB_TOKEN }} 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright © 2024-today, Andrea Giammarchi, @WebReflection 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the “Software”), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included 13 | in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 21 | IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "loop-once", 3 | "version": "1.0.4", 4 | "description": "A safer loop for sync or async unique use cases", 5 | "main": "./cjs/index.js", 6 | "scripts": { 7 | "build": "npm run cjs && npm run rollup:es && npm run ts && npm run test", 8 | "cjs": "ascjs --no-default esm cjs", 9 | "coverage": "mkdir -p ./coverage; c8 report --reporter=text-lcov > ./coverage/lcov.info", 10 | "rollup:es": "rollup --config rollup/es.config.js && sed -i.bck 's/^var /self./' es.js && rm -rf es.js.bck", 11 | "ts": "tsc -p .", 12 | "test": "c8 node test/index.js" 13 | }, 14 | "keywords": [ 15 | "loop", 16 | "async", 17 | "unique", 18 | "guard", 19 | "safe" 20 | ], 21 | "author": "Andrea Giammarchi", 22 | "license": "MIT", 23 | "devDependencies": { 24 | "@rollup/plugin-node-resolve": "^15.2.3", 25 | "@rollup/plugin-terser": "^0.4.4", 26 | "ascjs": "^6.0.3", 27 | "c8": "^9.1.0", 28 | "rollup": "^4.9.6", 29 | "typescript": "^5.3.3" 30 | }, 31 | "module": "./esm/index.js", 32 | "type": "module", 33 | "exports": { 34 | ".": { 35 | "types": "./types/index.d.ts", 36 | "import": "./esm/index.js", 37 | "default": "./cjs/index.js" 38 | }, 39 | "./package.json": "./package.json" 40 | }, 41 | "unpkg": "es.js" 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # loop-once 2 | 3 | [![Coverage Status](https://coveralls.io/repos/github/WebReflection/loop-once/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/loop-once?branch=main) 4 | 5 | **Social Media Photo by [Kier in Sight Archives](https://unsplash.com/@kierinsightarchives) on [Unsplash](https://unsplash.com/)** 6 | 7 | 8 | A safer loop to iterate synchronously or asynchronously any unique identifier. 9 | 10 | ```js 11 | import loopOnce from 'loop-once'; 12 | 13 | // create a function that will iterate 14 | // over whatever iterable is passed along 15 | // and arbitrary pass your own Set or WeakSet 16 | // as once would be otherwise created automatically. 17 | const unique = loopOnce(); 18 | 19 | // given a list of references 20 | // or primitives if a Set is passed along ... 21 | const iterable = [ 22 | Promise.resolve('a'), 23 | Promise.resolve('b'), 24 | Promise.resolve('c') 25 | ]; 26 | 27 | // no matter how many times this will be called 28 | // or how long it would take per each promise 29 | // to resolve ... 30 | const log = async () => { 31 | // the following loop will log once resolved promises 32 | for (const p of unique(iterable)) 33 | console.log(await p); 34 | }; 35 | 36 | // try it! 37 | log(); 38 | log(); 39 | log().then(log); 40 | setTimeout(log, 1000); 41 | 42 | // the output will be 43 | // "a" 44 | // "b" 45 | // "c" 46 | // and that's it 🥳 47 | ``` 48 | 49 | ### What exact problem does this module solve? 50 | 51 | The *TL;DR* story here is that too many times I ended up writing code as such: 52 | 53 | ```js 54 | const visited = new WeakSet; 55 | 56 | const bootstrap = async () => { 57 | for (const thing of things) { 58 | if (visited.has(thing)) { 59 | visited.add(thing); 60 | await init(thing); 61 | } 62 | } 63 | }; 64 | ``` 65 | 66 | Now I can use a single utility all over the place to do the same: 67 | 68 | ```js 69 | import loopOnce from 'loop-once'; 70 | const unique = loopOnce(); 71 | 72 | // every time I need to do the same ... 73 | const bootstrap = async () => { 74 | for (const thing of unique(things)) 75 | await init(thing); 76 | }; 77 | ``` 78 | 79 | That's it: I don't need to remember or worry about the fact `bootstrap` could be called many times while still executing and that `thing` should never be initialized twice. 80 | 81 | I hope this explanation reasons well with you too 👋 82 | --------------------------------------------------------------------------------