Export all functions in the current file as one variable - javascript

Suppose you have the following file:
graphService.js
const foo = () => { return 'foo' }
const bar = () => { return 'bar' }
How would it be possible to export all the functions so they can be used like this:
connsumer.js
import { graph } from 'src/services/graph/graphService'
graph.foo()
graph.bar()
With an extra file in between it's easy as you can do something like this:
graphMiddelFile.js
import * as graph from 'src/services/graph/graphCore'
export const graph = graph
Is this possible to do without a file in the middle and without using import * as graph from 'src/services/graph/graphService' in the consumer.js file?
I looked around the internet but couldn't find something similar. Thank you for your help.

If you are allowed to modify graphService, you can export an object.
export const graph = { foo, bar }

You can refer to: https://stackoverflow.com/a/33589850/10505608
As per this link:
Add in File 1
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
To access it in File 2
var Export = require('path/to/Exported');
Export.someFunction();
I have also tried it, works smoothly.

You can try something like this, hope that i understood your question
export const graph = {
foo: () => { return 'foo' },
bar: () => { return 'bar' }
};

The functions foo and bar can be defined as properties of an object in which case only the object can be exported and then the functions can be accessed accordingly where they are needed.
export service = {
foo : () => {return 'foo'},
bar : () => {return 'bar' }
}
console.log("service", service.foo())
console.log("service", service.bar())

Related

Add prototype of a fuction

I have some question about my node.js project.
What I'm trying to do is, add additional functionality to a function.
So, I added new functionality using prototype, but it failed.
Below is my current code.
[ someFeatures.js ]
const functionFoo = new Function()
const functionBar = new Function()
module.exports = { functionFoo, functionBar }
[ addFeatures.js ]
// Import fuction
const { functionFoo, functionBar } = require('./someFeatures.js')
// Add additional feature
functionFoo.prototype.addtionalFeatureA = foo => {
return someFunction(foo)
}
// Add additional feature
functionBar.prototype.addtionalFeatureB = foo => {
return someOtherFunction(foo)
}
module.exports = { functionFoo, functionBar }
[ Other files will use this feature ]
const { functionFoo } = require('./someFeatures.js')
const aaa = new functionFoo()
aaa.addtionalFeatureA('bbb')
The result is 'TypeError: Cannot read properties of undefined (reading 'prototype')'
Is there any solution to fix this issue? Thanks in advance!
change new Function
into empty function
let yourFunction = function () {}
and change this
function.prototype.additional = foo => { ... }
to this
function.prototype.additional = function (foo) {
...
}

How to write JavaScript code that allows for defaults to be overrided

I would like to use this text-highlighting library in my Vue project. Here's an example from their website of how it can be used:
import TextHighlighter from '#perlego/text-highlighter';
import { isDuplicate } from './utils';
import highlightsApi from './services/highlights-api';
class ArticleView {
constructor(data) {
this.data = data;
const pageElement = document.getElementById("article");
this.highlighter = new TextHighlighter(
pageElement,
{
version: "independencia",
onBeforeHighlight: this.onBeforeHighlight,
onAfterHighlight: this.onAfterHighlight,
preprocessDescriptors: this.preprocessDescriptors,
onRemoveHighlight: this.onRemoveHighlight
});
}
onBeforeHighlight = (range) => {
return !isDuplicate(range)
}
onRemoveHighlight = (highlightElement) => {
const proceed = window.confirm("Are you sure you want to remove this highlight?");
return proceed;
}
preprocessDescriptors = (range, descriptors, timestamp) => {
// Add an ID to the class list to identify each highlight
// (A highlight can be represented by a group of elements in the DOM).
const uniqueId = `hlt-${Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)}`;
const descriptorsWithIds = descriptors.map(descriptor => {
const [wrapper, ...rest] = descriptor;
return [
wrapper.replace(
'class="highlighted"',
`class="highlighted ${uniqueId}"`
),
...rest
];
});
return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
}
onAfterHighlight = (range, descriptors, timestamp, meta) => {
highlightsApi.saveBatch(meta.id, descriptorsWithIds)
.then((result) => {
// Do something with the highlights that have been saved.
})
.catch((err) => console.error(err));
}
render = () => {
// Code that takes the data for the article and adds it to the DOM
// based on a html template here.
}
}
Using the above example, I would like to setup the highlighter (similar to the above code, but in a different file, for example ./utils/highlighter.js) with all the default options I want (onBeforeHighlight, onRemoveHighlight, etc.), and then be able to import it from there and override the options for which I don't want to use the defaults, so it looks something like this in the importing file:
import highlighter from "../utils/highlighter.js";
const overridingOptions = {
onAfterHighlight: (range, descriptors, timestamp, meta) => {
console.log(range, descriptors, timestamp, meta);
}
};
const target = document.getElementsByClassName("testme")[0];
highlighter(target, overridingOptions);
For some reason, I am not able to understand how to modify the ArticleView example to fit my needs, so I think I need to see this done once. How should the code in ./utils/highlighter.js look to make this possible?

Exported function to pass arguments and a constant to another function

I don't really know how to describe this, but I'll try explain it.
I want to be able to call func1() and func2(), but going through handler() in a module.
I want it in a way where calling module.exported1("foo") will call handler(func1, "foo"), in turn calling func1("foo"). The issue I'm having is that if I export 'exported1' as handler(func1), I can't pass any arguments exported1 was called with (As far as I know). Is there a workaround for this?
NOTE: It is a module, and I need it to be exported without the user needing to provide func1 and func2 to handler().
function func1(args) {
...
}
function func2(args) {
...
}
function handler(func, args) {
return func()
}
module.exports = {
exported1 = handler(func1, ...),
exported2 = handler(func2, ...)
}
Not sure I get why to use this pattern, but I am sure there is more to the code and guess you could do the following:
function func1(args) {
console.info(`func1 ${args}`);
}
function func2(args) {
console.info(`func2 ${args}`);
}
function handler(func, args) {
return func(args);
}
module.exports = {
exported1: (args) => {
return handler(func1, (args));
},
exported2: (args) => {
return handler(func2, (args));
},
};
You just need to export the function:
module.exports = {
exported = handler
}
Or, just:
exports.exported = handler
Now, after import, you can call with parameters:
exported(func1,...)
exported(func2,...)
After reading your edited question, I think you want to do something like this but I'm not pretty sure:
function handler(func) {
// you can replace it with function(args) { instead of arrow function
return (args) => {
return func(args)
}
}
module.exports = {
exported1 = handler(func1),
exported2 = handler(func2)
}
exported1(args)

SDK API namespacing design

I like to implement like a namespacing something like this as example:
const { SMS } = require('./custom-sdk')
const list = SMS.List();
let data = list.getData("ABC");
console.log(data)
I am completely stuck how to implement this, what do I need to do design this kind of API methods.
I have tried like this would which would be in custom-sdk.js file:
module.exports = {
SMS: function() {
// ...
}
};
Would something like the following nesting work?
module.exports = {
SMS: {
List: function() {
return {
getData: function(arg) {
// get that data
}
}
}
}
};
Which I think would allow you to do SMS.List().getData('ABC'). That said, this seems overly nested, unless you just simplified it for the SO question. I would suggest to only use functions when necessary (to take an argument or to instantiate a service) and prefer just a plain object when possible:
module.exports = {
SMS: {
List: {
getData: function(arg) {
// get that data
}
}
}
};

Module variable as output of a method

I have a Javascript module:
const myModule = {
foo: this.initializeFoo(),
initializeFoo(){
// some loops and stuff to create an array
}
}
But I get an error: this.initializeFoo is not a function.
Is there some syntax I need to use to make this work, or is it not possible?
If you only intend to call it once and at the object's creation, then I would opt for a self-executing anonymous function:
const myModule = {
foo: (function () {
// some loops and stuff to create an array
})()
};
Alternatively, you can use arrow syntax instead:
const myModule = {
foo: (() => {
// some loops and stuff to create an array
})()
}
Example snippet:
const myModule = {
foo: (() => {
console.log('Processing');
return Array.apply(null, {length: 10}).map(Number.call, Number);
})()
};
// You can see that 'Processing' is only printed once
console.log(myModule.foo[2]);
console.log(myModule.foo[7]);
Declare the initializeFoo() function in outside of the Object
const myModule = {
foo : initializeFoo(),
}
function initializeFoo(){
return 'hi';
//or some loops and stuff to create an array
}
console.log(myModule)
If you can use ES6:
class MyModule {
constructor() {
this.initializeFoo();
}
initializeFoo() {
console.log('test');
// some loops and stuff to create an array
}
}
const myModule = new MyModule();
If you need to store the result of initializeFoo():
class MyModule {
constructor() {
this.initializeFoo();
}
initializeFoo(){
console.log('test');
this.initialVal = 2;
}
}
const myModule = new MyModule();
// 'test'
myModule.initialVal
// 2

Categories