Skip to content

This is a NPM Package based on JS , Which is basically gives an deep understanding How Inbuilt Js Functions , Methods Works Under the Hood , it can be much helpful those who are intermediate or new in js or preparing for an Job Preparation !! Happy Coding πŸ’–

License

Notifications You must be signed in to change notification settings

Rudrajiii/Js-Internals

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

26 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

github-header-image (2)

JavaScript Badge npm Badge Version Badge

Welcome to the Custom JavaScript Functions package! This npm package provides custom implementations of built-in JavaScript functions, allowing users to understand how these functions work internally. This is especially useful for learning purposes and for those who want to see how common JavaScript functions can be replicated.

Features πŸš€

  • Custom Implementations: Each function in this package is a custom implementation that mimics the behavior of the native JavaScript functions.
  • Educational: The primary goal of this package is to provide an educational resource for developers to understand the inner workings of JavaScript functions.
  • Polyfill-style Functions: These implementations can serve as polyfills, helping developers use similar functionality in environments where certain features may not be available.

Project Tree 🌳

πŸ“¦ js-internals
β”‚
β”œβ”€β”€ πŸ“‚ src
β”‚   β”œβ”€β”€ πŸ“‚ DataStructures
β”‚   β”‚   └── πŸ“„ set.js
β”‚   β”œβ”€β”€ πŸ“‚ internal-custom-functions
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ Array_Object
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“‚ Instance_Methods
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ _map.js
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ _filter.js
β”‚   β”‚   β”‚   β”‚   └── πŸ“„ _reduce.js
β”‚   β”‚   β”‚   └── πŸ“‚ Static_Methods
β”‚   β”‚   β”‚       β”œβ”€β”€ πŸ“„ _call.js
β”‚   β”‚   β”‚       β”œβ”€β”€ πŸ“„ _apply.js
β”‚   β”‚   β”‚       β”œβ”€β”€ πŸ“„ _from.js
β”‚   β”‚   β”‚       └── πŸ“„ _isArray.js
β”‚   └── πŸ“„ index.js
β”‚
β”œβ”€β”€ πŸ“‚ tests
β”‚   β”œβ”€β”€ πŸ“„ test.js
β”‚
β”œβ”€β”€ πŸ“„ package.json

Sample Code of custom $call(context, ...args) [Same as native call()]

/**
 * Function.prototype.call() - Calls a function with a given 'this' value and arguments provided individually.
 * The "call()" method allows you to invoke a function with a specific 'this' context, along with arguments passed individually. It is useful when you want to change the context ('this') for a particular function invocation.
 * @syntax :
 * @function.call(thisArg, arg1, arg2, ..., argN);

 * @thisArg : The value to use as 'this' when calling the function. If 'thisArg' is 'null' or 'undefined', it will default to the global object ('globalThis' in non-strict mode).
 * @arg1 , arg2, ..., argN: Individual arguments to pass to the function.

 * @returns:
 * The result of calling the function with the provided 'this' value and arguments.
**/

Function.prototype.__call = function(context, ...args) {
    if (typeof this !== "function") {
        throw new Error(this + " is not a function.");
    }

    if (context === undefined || context === null) {
        return this.apply(globalThis, args);
    }

    const boundContext = Object(context);

    boundContext.func = this;
    const result = boundContext.func(...args);
    delete boundContext.func;

    return result;
};

Progress ✨ ~

image

Available Functions πŸš€

Array Methods

Function Status Native Function
$Map(array, callback) Implemented βœ… Array.prototype.map()
$Filter(array, callback) Implemented βœ… Array.prototype.filter()
$Reduce(array, callback, initialValue) Implemented βœ… Array.prototype.reduce()
$Array.from(value) Implemented βœ… Array.from()
$Array.isArray(array) Implemented βœ… Array.isArray()
$Array.of(value) Implemented βœ… Array.of()
$ForEach(array, callback) Implemented βœ… Array.prototype.forEach()
$Some(array, callback) Implemented βœ… Array.prototype.some()
$Every(array, callback) Todo Array.prototype.every()
$Find(array, callback) Todo Array.prototype.find()
$IndexOf(array, element) Todo Array.prototype.indexOf()
$Includes(array, element) Todo Array.prototype.includes()
$Sort(array, compareFunction) Todo Array.prototype.sort()
$Reverse(array) Todo Array.prototype.reverse()
$Splice(array, start, deleteCount, ...items) Todo Array.prototype.splice()
$Slice(array, start, end) Todo Array.prototype.slice()
$Concat(array, ...arrays) Todo Array.prototype.concat()
$Join(array, separator) Todo Array.prototype.join()

String Methods

Function Status Native Function
$CharAt(string, index) Todo String.prototype.charAt()
$IndexOf(string, searchValue, fromIndex) Todo String.prototype.indexOf()
$Includes(string, searchString, fromIndex) Todo String.prototype.includes()
$Slice(string, start, end) Todo String.prototype.slice()
$Substring(string, start, end) Todo String.prototype.substring()
$Trim(string) Todo String.prototype.trim()
$ToLowerCase(string) Todo String.prototype.toLowerCase()
$ToUpperCase(string) Todo String.prototype.toUpperCase()
$Split(string, separator, limit) Todo String.prototype.split()
$Replace(string, searchValue, newValue) Todo String.prototype.replace()

Object Methods

Function Status Native Function
$Keys(object) Todo Object.keys()
$Values(object) Todo Object.values()
$Entries(object) Todo Object.entries()
$Assign(target, ...sources) Todo Object.assign()
$Freeze(object) Todo Object.freeze()
$Seal(object) Todo Object.seal()
$GetOwnPropertyDescriptor(object, property) Todo Object.getOwnPropertyDescriptor()
$Create(prototype, properties) Todo Object.create()
$HasOwnProperty(object, property) Todo Object.prototype.hasOwnProperty()

Function Methods

Function Status Native Function
$Call(func, thisArg, ...args) Implemented Function.prototype.call()
$Apply(func, thisArg, args) Implemented Function.prototype.apply()
$Bind(func, thisArg, ...args) Todo Function.prototype.bind()

Math Methods

Function Status Native Function
$Max(...numbers) Todo Math.max()
$Min(...numbers) Todo Math.min()
$Floor(number) Todo Math.floor()
$Ceil(number) Todo Math.ceil()
$Round(number) Todo Math.round()
$Random() Todo Math.random()
$Abs(number) Todo Math.abs()

Other Global Functions

Function Status Native Function
$ParseInt(string, radix) Todo parseInt()
$ParseFloat(string) Todo parseFloat()
$IsNaN(value) Todo isNaN()
$IsFinite(value) Todo isFinite()
$Stringify(value) Todo JSON.stringify()
$Parse(jsonString) Todo JSON.parse()

Hello Devs πŸ‘‹πŸ» If you want to contribute you are always Welcome !! Come and Contribute Here > 3 πŸ’—πŸ« 

Contribution Rule's

  • maintain existing file naming convension (eg. _file.js)
  • maintain existing code format for Contribution
  • ensure you write all the import tests for that func maintaining the proper format (eg. test_funcName.js)
  • demo test file for custom func $call()
const { __call } = require('../package/src/internal-custom-functions/Array_Object/Static_Methods/_call');

function deepEqual(obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
}

// Run tests for the custom __call method
const tests = [
    {
        description: 'Basic Function Call with Context',
        func: function(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; },
        context: { name: 'Alice' },
        args: ['Hello', '!'],
        expected: 'Hello, Alice!',
        testNumber: 0
    },
    {
        description: 'Function with No Context',
        func: function(num1, num2) { return num1 + num2; },
        context: undefined,
        args: [5, 10],
        expected: 15,
        testNumber: 1
    }
    //Write atleast 7-8 proper test cases.
];

// Run the tests
tests.forEach(test => {
    let result;
    let errorOccurred = false;
    try {
        result = test.func.__call(test.context, ...test.args);
    } catch (error) {
        if (test.expectedError) {
            errorOccurred = true;
            console.log(`Passed Test${test.testNumber} βœ…: ${test.description}`);
        } else {
            console.log(`Failed Test${test.testNumber} ❌: ${test.description}`);
            console.error('Unexpected Error:', error);
        }
    }

    if (!errorOccurred && deepEqual(result, test.expected)) {
        console.log(`Passed Test${test.testNumber} βœ…: ${test.description}`);
    } else if (!errorOccurred) {
        console.log(`Failed Test${test.testNumber} ❌: ${test.description}`);
        console.log(`Expected: ${JSON.stringify(test.expected)}`);
        console.log(`Actual: ${JSON.stringify(result)}`);
    }
});

Project SetUp

First Clone The Repo

git clone https://github.com/Rudrajiii/Js-Internals

Then Move To Project Directory

cd Js-Internals

Now Open Your Favourite Code Editor [ Mine is Vs-Code :) So ]

code .

Installation ⏬

To install this package, use npm:

npm install --save-dev js-internals

To Run The Tests: Make the test script executable: For (Linux):

chmod +x pkg_tester.sh

Run the test script:

./pkg_tester.sh

About

This is a NPM Package based on JS , Which is basically gives an deep understanding How Inbuilt Js Functions , Methods Works Under the Hood , it can be much helpful those who are intermediate or new in js or preparing for an Job Preparation !! Happy Coding πŸ’–

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published