Full Code of atapas/js-tips-tricks for AI

master 106eed3fb940 cached
9 files
17.4 KB
4.7k tokens
1 symbols
1 requests
Download .txt
Repository: atapas/js-tips-tricks
Branch: master
Commit: 106eed3fb940
Files: 9
Total size: 17.4 KB

Directory structure:
gitextract_maeansy9/

├── .github/
│   └── FUNDING.yml
├── LICENSE
├── README.md
├── index.html
├── index.js
├── merge-arrays/
│   ├── index.html
│   └── merge-arrays.js
├── object-destructuring.js
└── quiz-od.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [atapas]


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2021 Tapas Adhikary

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
# js-tips-tricks
List of JavaScript tips and tricks I am learning everyday!

- See it running here: https://stackblitz.com/edit/js-tips-tricks
- Read this blog for more insights: https://blog.greenroots.info/my-favorite-javascript-tips-and-tricks-ckd60i4cq011em8s16uobcelc

# Many Thanks to all the `Stargazers` who has supported this project with stars(⭐)

[![Stargazers repo roster for @atapas/js-tips-tricks](https://reporoster.com/stars/atapas/js-tips-tricks)](https://github.com/atapas/js-tips-tricks/stargazers)



================================================
FILE: index.html
================================================

<html>
    <head>
        <title>JavaScript Tips & Trics</title>
    </head>

    <body>
      <h1>All is in the browser console. Open it up.</h1>
        <script>
            const { log } = console;
            // 1. No Concatenation use Template string
            {
                let name = 'Charlse';
                let place = 'India';
                let isPrime = bit => {
                    return (bit === 'P' ? 'Prime' : 'Nom-Prime');
                }

                let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'
                log(messageConcat);

                let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`
                log(messageTemplateStr);
            }

            // 2. isNumber
            {
                let mynum = 123;
                let mynumStr = "123";
                let myNumFloat = 123.45;

                log(`${mynum} is a number?`, Number.isInteger(mynum));
                log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));
                log(`${myNumFloat} is a number?`, Number.isInteger(myNumFloat));
            }

            // 3. Value as Number
            function trackChange(event) {
                let value = event.target.value;
                log(`is ${value} a number?`, Number.isInteger(value));

                let valueAsNumber = event.target.valueAsNumber;
                log(`is ${value} a number?`, Number.isInteger(valueAsNumber));
            }

            // 4. Short hand with AND
            {
                let isPrime = true;
                const startWatching = () => {
                    log('Started Watching!');
                }
                if (isPrime) {
                    startWatching();
                }

                isPrime && startWatching();
            }

            // 5. Default values with OR
            {
                let person = {name: 'Jack'};
                let age = person.age || 35;
                log(`Age of ${person.name} is ${age}`);
            }

            // 6. Randoms
            {
                let planets = ['Mercury ', 'Mars', 'Venus', 'Earth', 'Neptune', 'Uranus', 'Saturn', 'Jupiter'];
                let randomPlanet = planets[Math.floor(Math.random() * planets.length)];
                log('Random Planet', randomPlanet);

                let getRandom = (min, max) => {
                    return Math.round(Math.random() * (max - min) + min);
                }
                log('Get random', getRandom(0, 10));
            }

            // 7. Function default params
            {
                let greetings = (name, message='Hello,') => {
                    return `${message} ${name}`;
                }
                
                log(greetings('Jack'));
                log(greetings('Jack', 'Hola!'));
            }

            // 8. Required Function Params
            {
                let isRequired = () => {
                    throw new Error('This is a mandatory parameter.');
                }

                let greetings = (name=isRequired(), message='Hello,') => {
                    return `${message} ${name}`;
                }
                log(greetings('Jack'));
            }

            // 9. Comma Operator
            {
                let count = 1;
                let ret = (count++, count);
                log(count);
            }

            // 10. Merging multiple objects
            {
                let emp = {
                    'id': 'E_01',
                    'name': 'Jack',
                    'age': 32,
                    'addr': 'India'
                };

                let job = {
                    'title': 'Software Dev',
                    'location': 'Paris'
                };

                // spread operator
                let merged = {...emp, ...job};
                log('Spread merged', merged);

                log('Object assign', Object.assign({}, emp, job));

                // for deep merge use _merge of lodash
            }

            // 11. Destructuring
            {
                // array
                let emojis = ['🔥', '⏲️', '🏆', '🍉'];
                let [fire, clock, , watermelon] = emojis;
                log(fire, clock, watermelon);

                let [f, ...rest] = emojis;
                log(f);
                log(rest);

                // object
                let shape = {
                    name: 'rect',
                    sides: 4,
                    height: 300,
                    width: 500
                };

                let {name, sides, ...restObj} = shape;
                log(name, sides);
                log(restObj);
            }

            // 12. Swap variables
            {
                let fire = '🔥';
                let fruit = '🍉';

                [fruit, fire] = [fire, fruit];
                log(fire, fruit);
            }

            // 13. isArray
            {
                let emojis = ['🔥', '⏲️', '🏆', '🍉'];
                log(Array.isArray(emojis));
                let obj = {};
                log(Array.isArray(obj));
            }

            // 14. undefined vs null
            {
                undefined == null // true
                undefined === null // false
            }

            // 15. Get Query Params
            {
                let project = new URLSearchParams(location.search).get('project');
            }

            // 16. Tagged Template Literals
            {
                function introduce(strings, ...values) {                                                        
                    let msg = 
                    `<span style="color:${values[1]}">
                        Hello ${values[0]}, Have a Nice Day! We know your favorite color is <u>${values[1]}</u>
                    </span>`;
                    
                    return msg;
                }

                const name = 'Joe';
                const color = 'green';

                const message = introduce`Hello, I'm ${name} and ${color} is my favorite color!`;

                log(message);
                document.body.innerHTML = message;
            }

        </script>
        <br />
        <input type='number' onkeyup="trackChange(event)" />

    </body>

</html>


================================================
FILE: index.js
================================================


================================================
FILE: merge-arrays/index.html
================================================
<html>
    <head>
        <title>JavaScript Tips & Trics</title>
        <script src="./merge-arrays.js"></script>
    </head>

    <body>
      <h1>All is in the browser console. Open it up.</h1>
    </body>
</html>

================================================
FILE: merge-arrays/merge-arrays.js
================================================
// Using for-loop
console.log('**** 1. Using for-loop ****');
{
  let merge = (first, second) => {
    for (let i = 0; i < second.length; i++) {
      first.push(second[i]);
    }

    return first;
  };

  let merged = merge([1, 2, 3], [4, 5, 6]);
  console.log(`merged using for loop is ${JSON.stringify(merged)}`);

  merged = merge(merge([1, 2, 3], [4, 5, 6]), [7, 8, 9]);
  console.log(`merged using for loop: ${JSON.stringify(merged)}`);
}

// Using Spread Operator
console.log('**** 2. Using Spread Operator ****');
{
  let arr1 = [1, 2, 3];
  let arr2 = [4, 5, 6];

  // Merge arrays
  let merged = [...arr1, ...arr2];
  
  console.log(`input array ${JSON.stringify(arr1)}`); // [1,2,3]
  console.log(`input array ${JSON.stringify(arr2)}`); // [4,5,6]
  console.log(`merged using spread operator: ${JSON.stringify(merged)}`); // [1,2,3,4,5,6]
  

  // let merged = [...arr1, ...arr2, ...arr3];
}

// Using the concat() method
console.log('**** 3. Using concat() Method ****');
{
  let arr1 = [1, 2, 3];
  let arr2 = [4, 5, 6];

  // Merge arrays
  let merged = arr1.concat(arr2);

  console.log(`input array ${JSON.stringify(arr1)}`); // [1,2,3]
  console.log(`input array ${JSON.stringify(arr2)}`); // [4,5,6]
  console.log(`merged using concat() method: ${JSON.stringify(merged)}`); // [1,2,3,4,5,6]
  

  // let merged = [].concat(arr1, arr2);
}

// Spread vs Concat
console.log('**** 3a. Spread vs Concat ****');
{
  let arr1 = [1, 2, 3];
  let name = 'Tapas';

  console.log(`input array ${JSON.stringify(arr1)}`); // [1,2,3]
  console.log(`input string ${name}`); // [4,5,6]

  const mergedUsingSpread = [...arr1, ...name];
  const mergedUsingConcat = arr1.concat(name);

  console.log(`mergedUsingSpread: ${JSON.stringify(mergedUsingSpread)}`);
  console.log(`mergedUsingConcat: ${JSON.stringify(mergedUsingConcat)}`);
}

// Using push() method
console.log('**** 4. Using push() Method ****');
{
  let arr1 = [1, 2, 3];
  let arr2 = [4, 5, 6];

  // Merge arrays
  let merged = arr1.push(...arr2);

  console.log(`merged using push() method: input array array1 changed to: ${JSON.stringify(arr1)}`); // [1,2,3]
  console.log(`input array array2 dodn't change: ${JSON.stringify(arr2)}`); // [4,5,6]

  arr1 = [1, 2, 3];
  arr2 = [4, 5, 6];
  arr3 = [7, 8, 9];

  // Merge arrays
  arr1.push(...[...arr2, ...arr3]);
}

// Using reduce() method
console.log('**** 5. Using reduce() Method ****');
{
  let arr1 = [1, 2, 3];
  let arr2 = [4, 5, 6];

  let merged = arr2.reduce((arr = [], item) => {
    arr.push(item);
    return arr;
  }, arr1);

  console.log(`input array ${JSON.stringify(arr1)}`); // [1,2,3]
  console.log(`input array ${JSON.stringify(arr2)}`); // [4,5,6]
  console.log(`merged using reduce() method: ${JSON.stringify(merged)}`); // [1,2,3,4,5,6]
}


================================================
FILE: object-destructuring.js
================================================

// 1. Destructure and pick a property
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const { name } = user;
    console.log(name);
}

// 2. Declaration Gotcha
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    { name  } = user // Uncaught SyntaxError: Unexpected token '='

    let name;
    { name  } = user; // user // Uncaught SyntaxError: Unexpected token '='

    ({ name  } = user)
    console.log(name); // Alex

}

// 3. Desctructure and pick multiple properties
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const { name, age } = user;
    console.log(name, age);
}

// 4. Assign new variable and default value
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }
    const {name, age, salary=123455} = user;
    console.log(name, age, salary)
}

// 5. Destructure and add aliases
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const { address: permanentAddress } = user;
    console.log(permanentAddress);
}

// 6. Destructuring nested objects
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43,
        'department':{
            'name': 'Sales',
            'Shift': 'Morning',
            'address': {
                'city': 'Bangalore',
                'street': '7th Residency Rd',
                'zip': 560001
            }
        }
    }

    const { department } = user; // {name: "Sales", Shift: "Morning", address: {…}}

    const { department: { address } } = user; // {city: "Bangalore", street: "7th Residency Rd", zip: 560001}

    const { department: { address: { city } } } = user; // Bangalore
}

// 7. Dynamic name property
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const getValue = key => {
        const { [key]: returnValue } = user;   
        return returnValue;
    }

    getValue('name') // Alex's
    getValue('age') // 43
}

// 8. Destructuring into Function Parameter
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    logDetails(user); // Alex is 43 year(s) old!

    function logDetails({name, age}) {
        console.log(`${name} is ${age} year(s) old!`)
    }
}

// 9. Destructure function return
{
    const getUser = () => {
        return{ 
            'name': 'Alex',
            'address': '15th Park Avenue',
            'age': 43
        }
    }

    const { name, address, age } = getUser();

    console.log(name, age, address);
}

// 10. Destructuring in loops
{
    const users = [{ 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    },
    { 
        'name': 'Bob',
        'address': 'Canada',
        'age': 53
    },
    { 
        'name': 'Carl',
        'address': 'Bangalore',
        'age': 26
    }];

    for(let { name, age } of users) {
        console.log(name)
    }
}

// 11. Destructure console.log 
{
    const { log, warn, error } = console;
}

// 12. Create a clone of an object
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const clone = {...user} // {name: "Alex", address: "15th Park Avenue", age: 43}

    clone === user; // false
}

// 13. Add properties to an object in Immutable way
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const updatedUser = {...user, salary:12345}; // {name: "Alex", address: "15th Park Avenue", age: 43, salary: 12345}

    console.log(user); // {name: "Alex", address: "15th Park Avenue", age: 43}
}

// 14. Update an object in Immutable way
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const updatedUser = {...user, age:56}; // {name: "Alex", address: "15th Park Avenue", age: 56}

    console.log(user); // {name: "Alex", address: "15th Park Avenue", age: 43}
}

// 15. Update Nested objects
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43,
        'department':{
            'name': 'Sales',
            'Shift': 'Morning',
            'address': {
                'city': 'Bangalore',
                'street': '7th Residency Rd',
                'zip': 560001
            }
        }
    }

    {...user, department: {'number': 006}} // department replaced

    {...user, department: {...user.department, 'number': 006}} // Right way
}

// 16. Combine two objects - Shallow Merge
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }

    const department = {
        'name': 'Sales',
        'Shift': 'Morning'
    }

    const completeDetails = {...user, ...department};

    console.log({completeDetails});
}

// 17. Rest operator in Object Destructuring
{
    const user = { 
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43
    }
    
    const {name, ...rest} = user;
    console.log(name, rest);

    const {age, ...rest} = user;
    console.log(age, rest);
}



================================================
FILE: quiz-od.js
================================================
/*

Here is a Quiz for you. Please have a look at the `dark_theme` object below.
Use the object destructuring, spread syntax and the rest parameter to achieve
the following:

1. Extract the value of the `font` property and assign it to a variable.
2. Extract the value of the `font` property and assign it to a variable with the
name `myFont`.
3. Extract the value of the button text color and link opacity.
4. Create a clone of the dark_theme object and add the `border-color` attribute 
with a color value.
5. Consider a `user` object like,
const user = {
    'name': 'Alex',
    'id': 'U_001'
}
Merge the user object to the `dark_theme` object.
6. Destructure the dark_theme object and put the link colors in a separate object 
using the rest parameter.

Feel free to fork the project and submit you answers by creating a file named,

`quiz-od-<github-username>.js`

*/

const dark_theme = {
    "id": "T_002",
    "name": "Dark",
    "colors": {
        "body": "#000000",
        "text": "#FFFFFF",
        "button": {
            "text": "#000000",
            "background": "#FFFFFF"
        },
        "link": {
            "text": "teal",
            "opacity": 1
        }
    },
    "font": "Roboto"
}

Download .txt
gitextract_maeansy9/

├── .github/
│   └── FUNDING.yml
├── LICENSE
├── README.md
├── index.html
├── index.js
├── merge-arrays/
│   ├── index.html
│   └── merge-arrays.js
├── object-destructuring.js
└── quiz-od.js
Download .txt
SYMBOL INDEX (1 symbols across 1 files)

FILE: object-destructuring.js
  function logDetails (line 118) | function logDetails({name, age}) {
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 64,
    "preview": "# These are supported funding model platforms\n\ngithub: [atapas]\n"
  },
  {
    "path": "LICENSE",
    "chars": 1071,
    "preview": "MIT License\n\nCopyright (c) 2021 Tapas Adhikary\n\nPermission is hereby granted, free of charge, to any person obtaining a "
  },
  {
    "path": "README.md",
    "chars": 519,
    "preview": "# js-tips-tricks\nList of JavaScript tips and tricks I am learning everyday!\n\n- See it running here: https://stackblitz.c"
  },
  {
    "path": "index.html",
    "chars": 6560,
    "preview": "\r\n<html>\r\n    <head>\r\n        <title>JavaScript Tips & Trics</title>\r\n    </head>\r\n\r\n    <body>\r\n      <h1>All is in the"
  },
  {
    "path": "index.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "merge-arrays/index.html",
    "chars": 216,
    "preview": "<html>\n    <head>\n        <title>JavaScript Tips & Trics</title>\n        <script src=\"./merge-arrays.js\"></script>\n    <"
  },
  {
    "path": "merge-arrays/merge-arrays.js",
    "chars": 2780,
    "preview": "// Using for-loop\nconsole.log('**** 1. Using for-loop ****');\n{\n  let merge = (first, second) => {\n    for (let i = 0; i"
  },
  {
    "path": "object-destructuring.js",
    "chars": 5374,
    "preview": "\n// 1. Destructure and pick a property\n{\n    const user = { \n        'name': 'Alex',\n        'address': '15th Park Avenu"
  },
  {
    "path": "quiz-od.js",
    "chars": 1214,
    "preview": "/*\n\nHere is a Quiz for you. Please have a look at the `dark_theme` object below.\nUse the object destructuring, spread sy"
  }
]

About this extraction

This page contains the full source code of the atapas/js-tips-tricks GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (17.4 KB), approximately 4.7k tokens, and a symbol index with 1 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!