Enhance all functions to have the callPolyfill method. The method accepts an object obj as its first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).
For example if you had the function:
function tax(price, taxRate) {
const totalCost = price * (1 + taxRate);
console.log(`The cost of ${this.item} is ${totalCost}`);
}
Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.
However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output.
Please solve this without using the built-in Function.call method.
The key insight is to temporarily assign the function as a property on the context object, which automatically sets the correct this binding when called. Best approach uses Symbol for unique property keys to avoid conflicts. Time: O(1), Space: O(1)
Common Approaches
✓
Memoization
⏱️ Time: N/A
Space: N/A
Backtracking
⏱️ Time: N/A
Space: N/A
Property Assignment Method
⏱️ Time: O(1)
Space: O(1)
Add the function as a property to the target object, call it with arguments, then clean up by deleting the property. This leverages JavaScript's method invocation to set the correct this context.
Symbol-based Property Assignment
⏱️ Time: O(1)
Space: O(1)
Similar to basic approach but uses Symbol() to create a unique property key, preventing any possibility of overwriting existing object properties. This is safer and more robust.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char function_body[10000];
char context_obj[1000];
double args[100];
int num_args = 0;
char string_args[10][1000];
int string_arg_indices[10];
int num_string_args = 0;
void trim_whitespace(char* str) {
int len = strlen(str);
while (len > 0 && isspace(str[len-1])) {
str[--len] = '\0';
}
int start = 0;
while (str[start] && isspace(str[start])) {
start++;
}
if (start > 0) {
memmove(str, str + start, len - start + 1);
}
}
void parse_function(char* line) {
// Extract function body
char* start = strstr(line, "{");
char* end = strrchr(line, "}");
if (start && end && start < end) {
start++;
int len = end - start;
strncpy(function_body, start, len);
function_body[len] = '\0';
trim_whitespace(function_body);
}
}
void parse_args(char* line) {
num_args = 0;
num_string_args = 0;
// Find the context object
char* ctx_start = strstr(line, "{");
char* ctx_end = strstr(ctx_start, "}");
if (ctx_start && ctx_end) {
int len = ctx_end - ctx_start + 1;
strncpy(context_obj, ctx_start, len);
context_obj[len] = '\0';
}
// Parse remaining arguments
char* p = ctx_end + 1;
while (*p) {
while (*p && (*p == ',' || *p == ' ' || *p == ']')) p++;
if (!*p) break;
if (*p == '"') {
// String argument
p++;
char* str_start = p;
while (*p && *p != '"') p++;
int len = p - str_start;
strncpy(string_args[num_string_args], str_start, len);
string_args[num_string_args][len] = '\0';
string_arg_indices[num_string_args] = num_args;
num_string_args++;
args[num_args++] = 0; // placeholder
if (*p == '"') p++;
} else if (isdigit(*p) || *p == '-') {
// Numeric argument
args[num_args++] = strtod(p, &p);
} else {
p++;
}
}
}
double extract_context_value(const char* key) {
char search[100];
sprintf(search, "\"%s\": ", key);
char* pos = strstr(context_obj, search);
if (pos) {
pos += strlen(search);
if (*pos == '"') {
return 0; // string value, return 0 as placeholder
}
return strtod(pos, NULL);
}
return 0;
}
char* extract_context_string(const char* key) {
static char result[1000];
char search[100];
sprintf(search, "\"%s\": \"", key);
char* pos = strstr(context_obj, search);
if (pos) {
pos += strlen(search);
char* end = strchr(pos, '"');
if (end) {
int len = end - pos;
strncpy(result, pos, len);
result[len] = '\0';
return result;
}
}
return "";
}
void solve() {
// Check which function we're dealing with based on function_body
if (strstr(function_body, "price * (1 + taxRate)")) {
// tax function
double price = args[0];
double taxRate = args[1];
double result = price * (1 + taxRate);
printf("%.0f\n", result);
}
else if (strstr(function_body, "Hello") && strstr(function_body, "this.title")) {
// greet function
char* name = string_args[0];
char* title = extract_context_string("title");
printf("Hello %s, I am %s\n", name, title);
}
else if (strstr(function_body, "Array.from(arguments)") && strstr(function_body, "reduce")) {
// sum function with arguments
double initial = extract_context_value("initial");
double sum = initial;
for (int i = 0; i < num_args; i++) {
sum += args[i];
}
printf("%.0f\n", sum);
}
else if (strstr(function_body, "a * b * this.factor")) {
// multiply function
double a = args[0];
double b = args[1];
double factor = extract_context_value("factor");
double result = a * b * factor;
printf("%.0f\n", result);
}
else if (strstr(function_body, "x + y * z + this.bonus")) {
// calculate function
double x = args[0];
double y = args[1];
double z = args[2];
double bonus = extract_context_value("bonus");
double result = x + y * z + bonus;
printf("%.0f\n", result);
}
}
int main() {
char line1[10000], line2[10000];
if (fgets(line1, sizeof(line1), stdin)) {
trim_whitespace(line1);
parse_function(line1);
}
if (fgets(line2, sizeof(line2), stdin)) {
trim_whitespace(line2);
parse_args(line2);
}
solve();
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
23.0K Views
MediumFrequency
~15 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.