return function as an object literal - javascript

In this exercise I can't figure out why if I return the function I get an error, while if I return the function as a literal object it works
(module.js not works)
module.exports = {eleva : allaSeconda()}
function allaSeconda(){
function calcola(num){
return num*num
}
return calcola
}
(module.js works)
module.exports = {eleva : allaSeconda()}
function allaSeconda(){
function calcola(num){
return num*num
}
return {calcola}
}
(index.js)
const {eleva} = require('./modulo')
console.log(eleva.calcola(9))

Your syntax is a little bit convoluted, you can simply:
// no need for parenthesis in the exports.
// you export a function that elevates
module.exports = {eleva : allaSeconda}
function allaSeconda(num){
return num*num
}
Which could also be done totally inline:
// no need for parenthesis in the exports.
// you export a function that elevates
module.exports = {
eleva: function(num) {
return num * num;
}
}
And you call it simply like so:
const {eleva} = require('./modulo')
console.log(eleva(9))
Please note that your first example works, if you call eleva directly.

Related

How to get arguments

The objective of this code is to write the rev function and make it return the following Obviously its
Maybe that's what you wanted. Since you are passing a function as a parameter you are using high order function or a decorator , hope this helps
check this here
function welcome(name) {
return `Welcome ${name}`;
}
function bye(name) {
return `Bye ${name}`;
}
function rev(wrapped) {
return function() {
const result = wrapped.apply(this,arguments);
return `${result}, ${result.split(" ").reverse().join(" ")}`
}
}
const revWelcome = rev(welcome);
const revBye = rev(bye);
console.log(revWelcome('James'))
console.log(revBye('Bond'))

Can't access inner function properly

Not sure if this is the right title but should be quick help.
Pretty much I keep on getting errors on testing a function because "TypeError: ParseThis.changeIt is not a function". Here's my code. What am I missing that causing this type error? Thanks!
const ParseThis = () => {
const changeIt = string => string;
return { changeIt: changeIt() }
}
Edit: More details!
Thanks for the help again
When you return your object, maybe you wanted to return the function and not the result of the call:
return { changeIt: changeIt };
or this which is more concise:
return { changeIt };
According to how you are using the translate function, I think you should export it this way:
const Translator = {
const translate = string => string;
};
if (module.exports) {
module.exports = Translator;
}
or this way:
const Translator = () => {
const translate = string => string;
return { translate };
}
if (module.exports) {
module.exports = Translator();
}
Return the function instead of calling it.
const ParseThis = () => {
const changeIt = string => string;
return { changeIt };
}
In the original post, changeIt() is a call to changeIt with no first parameter. It returns the value undefined. To return a function instead of calling it, omit the parenthesis.
Let's analyze your code.
Let's start from this:
const changeIt = string => string;
At this point, changeIt is a function that, given a parameter, it returns that a parameter.
Without an arrow function, if we should use the old classic named function, it would be like this:
function changeIt(parameter) {
return parameter;
}
What happens if you call changeIt() with no parameter? In javascript, when you pass no parameters ot a function, it's like you are passing undefined. So the function will return undefined.
Then you have this line:
return { changeIt: changeIt() }
But as we have seen, changeIt() is equal to undefined. So your code is equivalent to:
return { changeIt: undefined }
Which is clearly not a function!
What you probably meant to do, is not returning the result of function invokation, but return the function itself. So, instead that assigning changeIt(), just assign changeIt:
return { changeIt: changeIt }
Notice that you repeated twice the word changeIt, so you can get rid of this repetition and just write:
return { changeIt }
Your function is returning an object, so instead of
ParseThis.changeIt()
You should be doing something like
const a = ParseThis();
a.changeIt('some string');
But, note that even in your example, changeIt in the returning object is not a function.
Probably you are trying this
const ParseThis = () => {
const changeIt = string => string;
return { changeIt: changeIt};
}
Note that I've used { changeIt: changeIt}, setting changeIt to a reference of the inner function changeIt. And you are using { changeIt: changeIt()} setting changeIt to the value returned of the inner function changeIt. Those are two different operations.
The problem is that you are exporting a function, and not the object containing the nop function. You need to add parenthesis to your dummy:
const Translator = () => {
const translate = string => string;
return { translate };
};
if (module.exports) {
module.exports = Translator(); // add parenthesis here
}
Alternatively you could run the function you import, but I suspect that would be different from your real Translator api.

how to test reduce function inside exports function Jest(react)

I have a reducer in react which I am testing I want to test the return value of a reduce inside the exports default function. And I'm not sure how to get access to the reduce inside that function.
MyReducer:
exports default function myReducer({
people = [0,1,2];
people.reduce(function(sum, peeps){
return sum + peeps;
}0);
return "hey";
})
In jest test:
import myReducer from 'myReducer';
expectedPeeps = 3;
expect(Something needs to go here).toEqual(expectedPeeps);
I need to figure out how to get the return value of people.reduce. I can get "hey" by just invoking myReducer(). But how do I get the return value of people.reduce in my test! ?thanks in advance peeps.
First of all, you have several syntax issues in MyReducer. I think it should look like this:
export default function myReducer() {
const people = [0,1,2];
people.reduce(function(sum, peeps){
return sum + peeps;
}, 0);
return "hey";
}
If you need to test the reduce by itself, you could move it into its own function and export it:
export function reducePeople(people) {
return people.reduce(function(sum, peeps){
return sum + peeps;
}, 0);
}
export default function myReducer() {
people = [0,1,2];
reducePeople(people);
return "hey";
}
And import and test it in your tests:
import { reducePeople } from 'myReducer';
expectedPeeps = 3;
expect(reducePeople([0,1,2])).toEqual(expectedPeeps);

Closure compiler export Typescript classes and functions

I am trying to use closure compiler advanced mode on typescript generated classes with no success. Is there anyone who has accomplished such things.
Typescript Class
class TestData {
BlogName: string;
CacheTimeOut: number;
CopyrightHolder: string;
constructor(blogName: string, cacheTimeOut: number, copyrightHolder: string) {
this.BlogName = blogName;
this.CacheTimeOut = cacheTimeOut;
this.CopyrightHolder = copyrightHolder;
}
addBlog(value: string): boolean {
console.log('add blog');
return true;
}
validate(): boolean {
console.log('all valid');
return true
}
}
var myTestData = new TestData("name",22,"cpyright");
Generated Code
var TestData = (function () {
function TestData(blogName, cacheTimeOut, copyrightHolder) {
this.BlogName = blogName;
this.CacheTimeOut = cacheTimeOut;
this.CopyrightHolder = copyrightHolder;
}
TestData.prototype.addBlog = function (value) {
console.log('add blog');
return true;
};
TestData.prototype.validate = function () {
console.log('all valid');
return true;
};
return TestData;
})();var myTestData = new TestData();
This compiles into
new function() {};
I understand I should provide exports, so I added
window['TestData'] = TestData;
window['TestData'].prototype['addBlog'] = TestData.prototype.addBlog
window['TestData'].prototype['validate'] = TestData.prototype.validate
my output from closure compiler advanced compilation is
var a = function() {
function b() {
}
b.prototype.a = function() {
console.log("add blog");
return !0;
};
b.prototype.b = function() {
console.log("all valid");
return !0;
};
return b;
}();
window.TestData = a;
window.TestData.prototype.addBlog = a.prototype.a;
window.TestData.prototype.validate = a.prototype.b;
new a;
If you see there is still no constructor code that is left. This gets worse when we add this inside a module.
I also tried to use the #export of google closure wiht no success
I see couple of pluggins which can generate closure compiler annotations based on typescript, but those also doesnt generate proper code.
Thirdparty closure annotations generator
I ran a very basic test of this. Perhaps you changed your code and haven't re-tried.
If you compile the TypeScript in your question, it should result in the following JavaScript:
var TestData = (function () {
function TestData(blogName, cacheTimeOut, copyrightHolder) {
this.BlogName = blogName;
this.CacheTimeOut = cacheTimeOut;
this.CopyrightHolder = copyrightHolder;
}
TestData.prototype.addBlog = function (value) {
console.log('add blog');
return true;
};
TestData.prototype.validate = function () {
console.log('all valid');
return true;
};
return TestData;
})();
var myTestData = new TestData("name", 22, "cpyright");
In particular, the last line passes arguments to the TestData constructor.
A quick run of this results in (white-space is mine) using #compilation_level SIMPLE_OPTIMIZATIONS:
var TestData=function(){
function a(a,b,c){
this.BlogName=a;this.CacheTimeOut=b;this.CopyrightHolder=c
}
a.prototype.addBlog=function(a){console.log("add blog");return!0};
a.prototype.validate=function(){
console.log("all valid");return!0
};
return a
}(),myTestData=new TestData("name",22,"cpyright");
If you use advanced optimizations on partial code, it will be too aggressive. You need to supply all of your code for the Closure compiler to understand what really isn't used.
If your example represents all of your code, you'll notice that the constructor along with all three properties (BlogName, CacheTimeOut, and CopyrightHolder) are genuinely never used, so can be removed without affecting the behaviour of the program.
Answer: optimized noops are - wait for it - noops :)
Explanation:
If you use your gen code here http://www.closure-compiler.appspot.com/home
with ADVANCED_OPTIMIZATIONS it produces:
new function(){};
if you add myTestData.addBlog("test"); it produces:
(new (function(){function a(){}a.prototype.a=function(){console.log("add blog")};return a}())).a();

How do I wrap a function in Javascript?

I'm writing a global error handling "module" for one of my applications.
One of the features I want to have is to be able to easily wrap a function with a try{} catch{} block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting the code everywhere with try/catch blocks).
This is, however, slightly beyond my understanding of the low-level functioning of JavaScript, the .call and .apply methods, and the this keyword.
I wrote this code, based on Prototype's Function.wrap method:
Object.extend(Function.prototype, {
TryCatchWrap: function() {
var __method = this;
return function() {
try { __method.apply(this, arguments) } catch(ex) { ErrorHandler.Exception(ex); }
}
}
});
Which is used like this:
function DoSomething(a, b, c, d) {
document.write(a + b + c)
alert(1/e);
}
var fn2 = DoSomething.TryCatchWrap();
fn2(1, 2, 3, 4);
That code works perfectly. It prints out 6, and then calls my global error handler.
My question is: will this break something when the function I'm wrapping is within an object, and it uses the "this" operator? I'm slightly worried since I'm calling .apply, passing something there, I'm afraid this may break something.
Personally instead of polluting builtin objects I would go with a decorator technique:
var makeSafe = function(fn){
return function(){
try{
return fn.apply(this, arguments);
}catch(ex){
ErrorHandler.Exception(ex);
}
};
};
You can use it like that:
function fnOriginal(a){
console.log(1/a);
};
var fn2 = makeSafe(fnOriginal);
fn2(1);
fn2(0);
fn2("abracadabra!");
var obj = {
method1: function(x){ /* do something */ },
method2: function(x){ /* do something */ }
};
obj.safeMethod1 = makeSafe(obj.method1);
obj.method1(42); // the original method
obj.safeMethod1(42); // the "safe" method
// let's override a method completely
obj.method2 = makeSafe(obj.method2);
But if you do feel like modifying prototypes, you can write it like that:
Function.prototype.TryCatchWrap = function(){
var fn = this; // because we call it on the function itself
// let's copy the rest from makeSafe()
return function(){
try{
return fn.apply(this, arguments);
}catch(ex){
ErrorHandler.Exception(ex);
}
};
};
Obvious improvement will be to parameterize makeSafe() so you can specify what function to call in the catch block.
2017 answer: just use ES6. Given the following demo function:
function doThing(){
console.log(...arguments)
}
You can make your own wrapper function without needing external libraries:
function wrap(someFunction){
function wrappedFunction(){
var newArguments = [...arguments]
newArguments.push('SECRET EXTRA ARG ADDED BY WRAPPER!')
console.log(`You're about to run a function with these arguments: \n ${newArguments}`)
return someFunction(...newArguments)
}
return wrappedFunction
}
In use:
doThing('one', 'two', 'three')
Works as normal.
But using the new wrapped function:
const wrappedDoThing = wrap(doThing)
wrappedDoThing('one', 'two', 'three')
Returns:
one two three SECRET EXTRA ARG ADDED BY WRAPPER!
2016 answer: use the wrap module:
In the example below I'm wrapping process.exit(), but this works happily with any other function (including browser JS too).
var wrap = require('lodash.wrap');
var log = console.log.bind(console)
var RESTART_FLUSH_DELAY = 3 * 1000
process.exit = wrap(process.exit, function(originalFunction) {
log('Waiting', RESTART_FLUSH_DELAY, 'for buffers to flush before restarting')
setTimeout(originalFunction, RESTART_FLUSH_DELAY)
});
process.exit(1);
Object.extend(Function.prototype, {
Object.extend in the Google Chrome Console gives me 'undefined'
Well here's some working example:
Boolean.prototype.XOR =
// ^- Note that it's a captial 'B' and so
// you'll work on the Class and not the >b<oolean object
function( bool2 ) {
var bool1 = this.valueOf();
// 'this' refers to the actual object - and not to 'XOR'
return (bool1 == true && bool2 == false)
|| (bool1 == false && bool2 == true);
}
alert ( "true.XOR( false ) => " true.XOR( false ) );
so instead of
Object.extend(Function.prototype, {...})
Do it like:
Function.prototype.extend = {}
Function wrapping in good old fashion:
//Our function
function myFunction() {
//For example we do this:
document.getElementById('demo').innerHTML = Date();
return;
}
//Our wrapper - middleware
function wrapper(fn) {
try {
return function(){
console.info('We add something else', Date());
return fn();
}
}
catch (error) {
console.info('The error: ', error);
}
}
//We use wrapper - middleware
myFunction = wrapper(myFunction);
The same in ES6 style:
//Our function
let myFunction = () => {
//For example we do this:
document.getElementById('demo').innerHTML = Date();
return;
}
//Our wrapper - middleware
const wrapper = func => {
try {
return () => {
console.info('We add something else', Date());
return func();
}
}
catch (error) {
console.info('The error: ', error);
}
}
//We use wrapper - middleware
myFunction = wrapper(myFunction);
Here is an ES6 style:
const fnOriginal = (a, b, c, d) => {
console.log(a);
console.log(b);
console.log(c);
console.log(d);
return 'Return value from fnOriginal';
};
const wrapperFunction = fn => {
return function () {
try {
const returnValuFromOriginal = fn.apply(this, arguments);
console.log('Adding a new line from Wrapper :', returnValuFromOriginal);
} catch (ex) {
ErrorHandler.Exception(ex);
}
};
};
const fnWrapped = wrapperFunction(fnOriginal);
fnWrapped(1, 2, 3, 4);
The following wrapping utility takes a function and enables the developer to inject a code or wrap the original:
function wrap(originalFunction, { inject, wrapper } = {}) {
const wrapperFn = function(...args) {
if (typeof inject === 'function') {
inject(originalFunction, this);
}
if (typeof wrapper === 'function') {
return wrapper(originalFunction, this, args);
}
return originalFunction.apply(this, args);
};
// copy the original function's props onto the wrapper
for(const prop in originalFunction) {
if (originalFunction.hasOwnProperty(prop)) {
wrapperFn[prop] = originalFunction[prop];
}
}
return wrapperFn;
}
Usage example:
// create window.a()
(function() {
const txt = 'correctly'; // outer scope variable
window.a = function a(someText) { // our target
if (someText === "isn't") {
throw('omg');
}
return ['a', someText, window.a.c, txt].join(' ');
};
window.a.c = 'called'; // a.c property example
})();
const originalFunc = window.a;
console.log(originalFunc('is')); // logs "a is called correctly"
window.a = wrap(originalFunc);
console.log(a('is')); // logs "a is called correctly"
window.a = wrap(originalFunc, { inject(func, thisArg) { console.log('injected function'); }});
console.log(a('is')); // logs "injected function\na is called correctly"
window.a = wrap(originalFunc, { wrapper(func, thisArg, args) { console.log(`doing something else instead of ${func.name}(${args.join(', ')})`); }});
console.log(a('is')); // logs "doing something else instead of a(is)"
window.a = wrap(originalFunc, {
wrapper(func, thisArg, args) {
try {
return func.apply(thisArg, args);
} catch(err) {
console.error('got an exception');
}
}
});
a("isn't"); // error message: "got an exception"
The last example demonstrates how to wrap your function with a try-catch clause
As far as polluting the namespaces, I'm actually going to pollute them some more...
Since everything that happens in JS is initiated by an event of some kind, I'm planning to call my magical wrapper function from within the Prototype Event.observe() method, so I don't need to call it everywhere.
I do see the downsides of all this, of course, but this particular project is heavily tied to Prototype anyway, and I do want to have this error handler code be as global as possible, so it's not a big deal.
Thanks for your answer!

Categories

Resources