Subprograms
Subprograms
Fundamentals of Subprograms
A subprogram is a program inside a larger program that can be used multiple times in multiple places. Each subprogram can have only one entry point and execute one at a time. All calling programs will be suspended during subprogram execution.
A subprogram header contains:
name of the subprogram
type of the subprogram
a list of parameters (optional)
Subprogram name: SummarizeDocs
Subprogram type: 'async' asynchronous function using 'await' to call 'summarizeWithHuggingFace' function
Parameters: docs, docType
Parameters
There are two types of parameters, the formal parameter and the actual parameter.
Formal parameter
Formal parameters or formal arguments represent the data that the function is expected to receive when called in the subprogram. In this sample application subprogram, the formal parameter is 'docs' and 'docType'.
Actual parameter
Actual parameters or actual arguments are the value of the formal parameter that is called during execution. The actual parameters in this sample application subprogram are 'd' and 'TXT'.
Procedures are a category of subprograms that contain blocks of codes that perform a task or calculate a value. There are two methods to produce results in calling program unit:
If there are variables that aren't formal parameters but are still visible in both the procedure and the calling program unit, the procedure can change them
The procedure has formal parameters that allow the transfer of data to the caller, those parameters can be changed.
Functions that do not return a value can be considered as a procedure.
The function "promptUserForQuestions" can be considered as a procedure as it does not return a value.
Similar to a procedure, a function is more semantically modeled on mathematical functions. It is executed once invoked. A function consists of:
1. 'function' keyword
2. the function name
3. a list of parameters
4. statements enclosed in curly braces
this function is defined using arrow (=>) function
the name of this function is "summarizeWithHuggingFace"
the parameters are listed in the brackets beside the function name
the statements of the function is enclosed in curly braces
(Concepts of Programming Language, n.d.)
- Anis Syifaa'
DESIGN ISSUES FOR SUBPROGRAMS
Local Referencing Environments
Subprograms have a complex structure, hence a lot of design issues arise, especially on deciding the multiple choice of parameter passing methods. Variables declared in the subprograms are called local variables, meaning they can only be called within the same subprogram.
Can local variable be stack-dynamic?
JavaScript has a stack-based memory management system, therefore local variables stored in the memory can be stack-dynamic.
Stack-dynamic local variables are bound to storage when the subprogram begins to run and are unbound when execution stops.
Advantages:
Promotes flexibility, especially for recursive subprograms
Storage for local variables in the current subprogram can be shared with other variables in an inactive subprogram.
Disadvantages:
Time-consuming, because each call needs to allocate, initialize, and deallocate memory to and from a variable.
Access to static-dynamic variables is indirect because the memory location of a local variable can only be determined during execution. This requires the CPU to calculate the memory address beforehand, requiring an extra process.
It is not history-sensitive as it quickly discards the variable from a memory location as soon as execution ends.
Can local variables be static?
JavaScript does not have 'static' keyword for local variables like Java. However, it does have 'static' keyword for method and property of a class.
In this block of code, the user tries to declare a local variable 'summaries' as static. This will cause SyntaxError as JavaScript does not have 'static' keyword for local variables.
However, we can still simulate similar static-like behavior to local variables by using nested subprograms, static methods and closures.
(Concepts of Programming Language, n.d.)
- Anis Syifaa'
Parameter-Passing Methods
JavaScript supports pass-by-value and pass-by-reference depending on the variables or data.
The method used by JavaScript is pass-by-value for primitive values like integer, float, string, number, boolean, null, undefined, symbol, and bigint. The value is passed to a function without any changes and modifications happened.
For instance, text and docType a primitive value that is passed-by-value in the summarizeWithHuggingFace function. The value is unchangeable and only for functions called as if the value will be copied and passed. This also shows the in mode of semantic models in JavaScript of reading the value without any modification happening.
Another method used is pass-by-reference for objects, arrays, and functions. The reference to the original memory location will be changed when a function is passed.
The docs parameter is the functions that are being passed-by-reference.
Additionally, JavaScript does not support inout mode parameter passing because it can not directly return a value through a parameter.
- Nur Insyirah Iman
Calling Subprograms Indirectly
Indirectly called subprograms often occur in situations when the specific subprograms to be called are not known until run time (Sebesta, 2012). In JavaScript, subprograms can be invoked indirectly using call(), apply(), bind(), or callbacks.
1. call()
The call() method is a pre-defined JavaScript method. It can be used to invoke a method or subprogram with an owner object as an argument (parameter) (GeeksforGeeks, 2024).
A const demoObject is the function created to use for call() method.
The call() method is used to invoke the describe() function, with using ({name: "Document Loader"}) as the thisArg.
2. apply()
The apply() method is used to write methods that can be used on different objects, which takes arguments as an array (GeeksforGeeks, 2023).
A const demoObject is the function created to use for apply () method.
The apply() method changed this.name to "Summary" and the format parameter to "Apply".
3. bind()
The bind() method creates a new function, and when that new function is called, it sets this keyword to the first argument, which is passed to the bind() method. If any other sequences of arguments preceding the first argument are passed to the bind() method, then they are passed as an argument to the new function when the new function is called (GeeksforGeeks, 2024).
A const demoObject is the function created to use for bind() method.
bind() returns a new function boundDescribe that can be called later, unlike call() and apply().
The boundDescribe function is invoked with the argument "Bind", which is passed as the format parameter to the orgiinal describe method.
4. Callbacks
A callback is a function passed as argument to another function, which allows the latter to execute the callback function at a specific time, often after completing an operation. Callbacks are a fundamental concept in JavaScript to allow asynchronous programming and modular code design (GeeksforGeeks, 2024).
The processWithCallback function takes summarytText as an argument that generated the summarization of the document.
The processWithCallback function also takes function data as a callback.
- Sofia Batrisyia
Design Issues for Functions
Functional Side Effects
Side effects in Javascript refer to the concept of a function that can alter the external state of the specific application. By means, the function can alter parts or values of the application that do not directly reside inside the same method. Nevertheless, there are 2 common cases where a function can produce a side effect (Ijemma Onwuzulike, 2020).
1. Alter Outer Variable
A function can go to its outer scope and directly adjust the values of outer variables.
2. Alter Method Arguments
A function directly mutates or alters the value of its provided argument.
However, JavaScript has pure functions, in which they return the same output given the same input, and does not have any side effects.
Types of Values Returned
The return statement is used to return a particular value from the function to the function caller. The function will stop executing when the return statement is called. In JavaScript, primitive values and object types can be returned by using the return statement (JavaScript Return - Javatpoint, n.d.).
Number of Returned Values
In JavaScript, multiple values can be returned by packing them as elements of an array or as properties of an object (GeeksforGeeks, 2024).
The approach of using an array to return multiple values from a function involves values organization into an array, then utilize the destructuring of the array to extract and assign those values to individual variables.
The approach of using an object to return multiple values from a function involves organizing the values into key-value pairs within an object.
- Sofia Batrisyia
Overloaded Subprograms
Function Overloading is a feature in many object-oriented programming languages that allows multiple functions or methods to share the same name but different signatures, where the implementations of the parameter, such as the number or type of arguments passed.
Unlike other programming languages, JavaScript does not support subprogram overloading. This is because JavaScript functions are dynamically typed and do not strictly enforce parameter types or counts which means that variable types are checked during runtime instead of during compilation. As JavaScript treats functions as objects, redefining a function with the same name simply reassigns its reference, so the last defined function will overwrite the previous ones.
However, function overloading in JavaScript can be simulated by checking the number or types of arguments using tools like the arguments object, rest parameters, or type checks. JavaScript supports function overriding, where the most recently defined function with a given name takes precedence and will be executed whenever the function is called.
(www.naukri.com, n.d.-b) (GeeksforGeeks, 2024c)
This example proved that JavaScript does not support function overloading natively. The second function foo(arg1, arg2) overwrites the first function foo(arg1). When foo(“TPL Project”) is called, the function with two parameters is called, but the second argument remains undefined because only one argument was passed.
(GeeksforGeeks, 2024b)
The example below shows how function overloading is simulated using conditionals to check the number and type of arguments passed to the functions. The function behaves differently based on how it is called.
Output:
The function first examines how many arguments are passed to it using arguments.length.
Then, it decides which function to execute based on the types of arguments.
If there is one argument, it checks:
If it's an array, it calls function3.
If it’s not an array, it calls function1.
If there are two arguments, it calls function2.
(GeeksforGeeks, 2024b)
Sample Application
All functions (summarizeWithHuggingFace, summarizeDocs, promptUserForQuestions, main) have unique names, and there are no instances of multiple functions with the same name but different parameter lists.
To incorporate overloaded subprograms in our sample application, the function summarizeWithHuggingFace is overloaded with two versions to handle single text and batch text inputs. The single text input version accepts a single text string as input and summarize one document at a time. For batch processing, it accepts an array of texts for batch summarization. They share the same name but handle different use cases by varying the parameters.
- Kueh Pang Teng
User-Defined Overloaded Operators
Operator overloading is a feature used to redefine or "overload" the standard behaviour of operators (such as +, -, *, etc.) to work with user-defined data types. This is useful when dealing with objects of custom classes (GeeksforGeeks, 2024a).
This is a form of abstraction by allows developers to perform complex operations in a single line of code. It shortens the amount of code needed to complete tasks while making the code easier to read and understand. This can be especially useful when handling large datasets or complex operations.
Operator overloading allows developers to use these operators to provide specific functionality based on their use case. For instance, the “+” operator can be used to add two numbers or concatenate two strings together depending on the context. Although JavaScript does not natively support operator overloading, it can be implemented using libraries or experimental features in certain environments.
(Kumari, 2024) (Npm: Operator-overloading, n.d.)
To enable simple operator overloading in JavaScript, which is compatible with Node.js environment, the following command can be used to install the library using npm:
npm install operator-overloading --save
Output:
This program demonstrates operator overloading in JavaScript using the operator-overloading library.
The __plus method defines what happens when two Student objects are added.
It creates a new Student object with:
A combined name: Joining the names of the two objects with a +.
A combined mark: Adding the marks of the two objects.
The following operators can be overloaded with their respective overload function names using the package:
(Npm: Operator-overloading, n.d.)
Sample Application
The operators in our sample application such as + is used for string concatenation while logical operators like &&, and relational operators like === are used in default behaviours. Since JavaScript does not support user-defined overloaded operators natively, we can use classes with methods to simulate this behavior.
In this example, the DocumentSummary class use a combine method that mimics the + operator to merge summaries. The toString method formats the output nicely. It acts as a custom way to "add" two DocumentSummary objects and emulates the + operator by creating a new object that contains the combined content and summary.
- Kueh Pang Teng
REFERENCES
Fundamentals of Subprograms
Concepts of programming language (tenth). (n.d.). Pearson.
MDN Web Docs. (2024, November 14). Functions - JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Local Referencing Environments
Concepts of programming language (tenth). (n.d.). Pearson.
GeeksforGeeks. (2024, August 20). Global and Local variables in JavaScript. GeeksforGeeks. https://www.geeksforgeeks.org/global-and-local-variables-in-javascript/
Parameter-Passing Methods
GeeksforGeeks. (2024, September 16). Pass by value and pass by reference in Javascript. GeeksforGeeks. https://www.geeksforgeeks.org/pass-by-value-and-pass-by-reference-in-javascript/
W3Schools.com. (n.d.). https://www.w3schools.com/js/js_const.asp
Calling Subprograms Indirectly
GeeksforGeeks. (2024, December 17). JavaScript function invocation. GeeksforGeeks. https://www.geeksforgeeks.org/javascript-function-invocation/
GeeksforGeeks. (2024, December 13). JavaScript callbacks. GeeksforGeeks. https://www.geeksforgeeks.org/javascript-callbacks/
GeeksforGeeks. (2024, August 20). Explain call(), apply(), and bind() methods in JavaScript. GeeksforGeeks. https://www.geeksforgeeks.org/explain-call-apply-and-bind-methods-in-javascript/
GeeksforGeeks. (2024, June 5). JavaScript Function call. GeeksforGeeks. https://www.geeksforgeeks.org/javascript-function-call/
GeeksforGeeks. (2023, May 26). JavaScript Apply() function. GeeksforGeeks. https://geeksforgeeks.org/javascript-apply-function/
Sebesta, R. W. (2012). Concepts of Programming Languages (Tenth). Pearson Education, Inc.
Design Issues for Functions
GeeksforGeeks. (2024, June 4). JavaScript Return multiple values from function. GeeksforGeeks. https://www.geeksforgeeks.org/javascript-return-multiple-values-from-function/
GeeksforGeeks. (2024, February 2). How to use Return in JavaScript ? GeeksforGeeks. https://www.geeksforgeeks.org/how-to-use-return-in-javascript/
Ijemma Onwuzulike. (2020, July 13). JavaScript pure functions and side effects in 8 minutes [Video]. YouTube. https://www.youtube.com/watch?v=LR2z-a7VwmQ
JavaScript return - javatpoint. (n.d.). www.javatpoint.com. https://www.javatpoint.com/javascript-return
Overloaded Subprograms
naukri.com. (2024). Code 360 by Coding Ninjas. https://www.naukri.com/code360/library/function-overloading-in-typescript
GeeksforGeeks. (2024, September 18). Function overloading in JavaScript. GeeksforGeeks. https://www.geeksforgeeks.org/function-overloading-in-javascript/
User-Defined Overloaded Operators
GeeksforGeeks. (2024, May 29). Operator overloading in programming. GeeksforGeeks. https://www.geeksforgeeks.org/operator-overloading-in-programming/
Kumari, N. (2024, May 5). Javascript operator overloading: Javascript explained. Bito. https://bito.ai/resources/javascript-operator-overloading-javascript-explained/
npm. (n.d.). operator-overloading. Npm. https://www.npmjs.com/package/operator-overloading