inf3rno
inf3rno

Reputation: 26129

Cannot add Object.assign to google sheets

I added something like this to an utils.gs file in google sheets:

Object.assign = function (target, source){
  if (!target || !source)
    throw new Error("Invalid arguments.");
  for (var property in source)
    if (source.hasOwnProperty(property))
      target[property] = source[property];
};

In the same script file I defined a function which depends on Object.assign, but I always got an error message:

TypeError: Cannot find function assign in object function Object() { [native code for Object.Object, arity=1] }.

Any idea why I cannot add it?

Upvotes: 0

Views: 1104

Answers (1)

inf3rno
inf3rno

Reputation: 26129

This is some sort of bug in the module system.

This code works:

main.gs

Object.assign = function (target, source){
  if (!target || !source)
    throw new Error("Invalid arguments.");
  for (var property in source)
    if (source.hasOwnProperty(property))
      target[property] = source[property];
  return target;
};

Logger.log(Object.assign({}, {a:1}));

function main(){
  Logger.log(Object.assign({}, {a:1}));
}

But if I move the Object.assign to a separate file:

main.gs

Logger.log(Object.assign({}, {a:1}));

function main(){
  Logger.log(Object.assign({}, {a:1}));
}

assign.gs

Object.assign = function (target, source){
  if (!target || !source)
    throw new Error("Invalid arguments.");
  for (var property in source)
    if (source.hasOwnProperty(property))
      target[property] = source[property];
  return target;
};

then only the second Object.assign() works, which is called in the main() function. If I define and call assign() instead, then both works.

Note that this is normally not a problem, because you usually don't add both lines to the main.gs. If you use utility functions to help prototype creation, then it is better to move every constructor and prototype definition to a separate file instead of defining them in the main.gs. That way you won't have such problems and you can use Object.assign even in your other utility functions and definitions.

Upvotes: 1

Related Questions