What's a good alternative to Object.assign? - javascript

I have
var shared = {
}
var stuff = Object.assign(Object.create(shared),{
//stuff
});
But Object.assign doesn't work on Safari and I don't wanna use something like Babel since my website is already kinda laggy. Is there any good alternative to make it so I can do this while maintaining "stuff" inheritance to "shared"..
var shared = {
}
var stuff = Object.create(shared);
stuff = {//stuff
};
I realize I can simply assign properties one by one to "stuff" but I have a lot of properties there and it would make the code a lot less organized

If you want another way to copy properties, how about something like this (copies everything from A to B):
const a = {hello:1, world:2};
const b = {};
Object.keys(a).forEach(k => b[k] = a[k]);
// b is now {hello:1, world:2}.

If you want quick dirty solution with minimal change to your codebase, try this pkg https://github.com/rubennorte/es6-object-assign
In my opinion, you should use bundling framework, say webpack, alongside with babel. There are many ways to reduce the bundled file size like tree-shaking, minifying, separating vendor files and sending JS files gzipped to the browser and it is not laggy at all.

Related

Need to import non ES6 library without export to VueJS

I have a strange problem to solve.
In a future VueJS project we need to use a library which is quite outdatet but there is no time to rewrite it.
It is a JS file containing a lot of silly var's declared, some functions and prototypes.
It is mainly structured like this:
var t1 = 'test1';
var i1 = 2;
function testclass(arg) {
object1 = this;
this._t1 = null;
return object1;
}
testclass.prototype = {
dosth: function () {
console.log('doing');
}
}
But its about 10.399 Lines of code so no way of rewriting it to a object or integrating export to each function.
Do you guys have any good idea or tool to manage this problem.
The only whay until now would be to import it seperatly as script tag but then our linter would cry and it also would look quite ugly.
Use eslint cli and run it with the --fix flag. This can fix a lot of these issues with the linter. https://eslint.org/docs/user-guide/migrating-from-jscs#--fix
Other than stylistic changes and es6 syntactic sugar, it will work just fine in the browser, so there's no need to rewrite anything.

How do I keep functions out of the global namespace when using multiple files?

Last time I built a large-scale application with JS I used require.js - which is great, but can be quite an overhead, especially if you don't want to load files asychronously, so this time I'm going without it.
This time I'm writing in pure JS and concatenating and minifying everything with Grunt (I'm a Grunt n00b here). Because I'm keeping all the functions in separate files, I can't wrap everything in a closure like I could if I was using a single file. What's the best solution to keeping all functions out of the global namespace?
I'm not sure I need a full dependency management solution, but I'd consider one if it's lightweight and simple.
If you want to do it without any dependency management tool you can for example use the Revealing Module Pattern and namespaces, simplified example:
Top/Application file
window.SomeApplication = (function () {
// Add functions you want to expose to this
this.require= function (path) { // Creates namespace if not already existing, otherwise returns reference to lowest level object in path
var current = window,
i;
path = path.split('.');
for (i = 0; i < path.length; ++i) {
if (!current[path[i]]) {
current[path[i]] = {};
}
current = current[path[i]];
}
return current;
};
return this;
})();
Some other file
SomeApplication.require('SomeApplication.SomeSubNamespace').SomeModule = (function () {
// Module code
return this;
})();
Then use your grunt concat and specify the top file first. This way you will only expose one item on the window object and your module will be accessible through window.SomeApplication.SomeSubNamespace.SomeModule.
There are a number of common and easy to use JavaScript tools for managing application-wide dependencies by either implementing the CommonJS (the specification used by require.js) or the ES2015 module specification, including (as Benjamin suggested) Webpack, Browserify, and Rollup.

Convert a large javascript file into multiple files

My question: How would one best go about breaking a large, monolithic javascript object literal into multiple, discrete, files?
I have a single javascript file that consists of an object literal with many methods attached to it. It's getting quite long and I want to break it into smaller parts that can more easily be managed.
I've heard I can use AMD or CommonJS to organize things, I've heard I should use RequireJS, that I should use Webpack or Browserify, that I should use any number of other tools/techniques. After looking at these things I am confused as to what the best approach is.
How would you do it? How would you take a single object literal consisting of a few thousands lines of javascript (made up of functions like "search" and "login" and "user") and reorganize it into multiple files that are more easily dealt with by a group of developers? The single, giant file thing is just getting to unwieldy and the options seems to varied and unclear. This is a fairly simple app that uses vanilla JS, a little jQuery and sits on top of a Grails backend.
I think the question is pretty clear but if you really need code to look at here is an example of the sort of object literal I am talking about:
var myObj = {
foo: "one",
bar: "two",
baz: false,
deez: -1,
login: function() {
// lots and lots of code
},
user: function() {
// lots and lots of code
},
beers: function() {
// lots and lots of code
},
varieties: function() {
// lots and lots of code
}
init: function() {
myObj.login.init();
myObj.user.init();
// lots of jQuery document.ready stuff
}
}
myObj.init();
You will a lot of suggestions and approaches to solve your problems, and I can't say any of them are wrong, they are just different.
My approach would be to use ES6 and its native module support.
To accomplish this I always use my own boilerplate named fabric which uses Webpack to compile the modules, Browsersync to help you on your development, Tape for unit testing, SASS for your CSS preprocessing, and Babel to compile a compatible ES5 bundle that you can easily use in your application.
Now, the way to use the ES6 modules is something like this with named exports:
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
Or using default exports:
//------ myFunc.js ------
export default function () { ... };
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();
You can learn more about ES6 modules at 2ality
Here's the pattern I use:
When possible, break concepts into their own sub-object
Regardless of sub-objects or not, declare any non-broken-up properties first, then add to it as needed
If the files are across multiple files and you do not wish to use sub-objects per-file, use a temporary object to hold additional properties, and then extend the original.
Sample:
var myObj = {
foo: "one",
bar: "two",
baz: false,
deez: -1
}
myObj.login = function() {
// lots and lots of code
};
myObj.user = function() {
// lots and lots of code
};
myObj.drinks = {
beer: function() {},
wine: function() {},
sunnyDelight: {
drinkIt: function() {},
burp: function() {}
}
};
myObj.init = function() {
myObj.login.init();
myObj.user.init();
// lots of jQuery document.ready stuff
}
myObj.init();
Note that "drinks" is a concept unto itself, containing multiple properties and methods. Your concepts might be something like "ui", "utils", "data" or whatever the role of the contained properties happens to be.
For the extend point I made, there's not much code needed there either
// "utilities.js"
var myObj = {
// a bunch of properties and/or methods
};
myObj.moreStuff = "more stuff!";
and then in another file you have two choices. Either add to the object without overwriting it (you will need the dot-notation to do this):
// "ui.js"
var myObj = myObj || {};
// adds the render object to the existing myObj
myObj.render = {
header: function() {},
dialogBox: function() {}
}
The above works particularly well if you sub-divide your concepts... because you can still have fairly monolithic objects that will not trample over the rest of myObj. But maybe you want to add directly to myObj without trampling and without subdividing concerns:
// "ui.js"
var myObj = myObj || {};
// ultimately, the CONTENTS of this object get merged into the existing myObj
var myObjSupplement = {
header: function() {},
dialogBox: function() {},
heroBiscuit: "A yummy biscuit made from heroes!"
}
// using jQuery here, but it's not the only way to extend an object
$.extend(myObj, myObjSupplement)
I don't see TOO many opportunities to use the above, since myObjSupplement is now in the global namespace and defeats the purpose of limiting additions to the global namespace, but it's there if you need it.
[edited to add: ]
It might not go "without saying" as I thought-- but dividing into many different files probably works best if you have a build process in place that can concatenate them into one file suitable for minifying. You don't want to have 100 or even 6 separate files each requiring a synchronous HTTP call to fetch.
There are more modern and possibly 'better' approaches with technologies like AMD/RequireJS... but if the question is, "how do I divide up an object literal into several files", the above answer I've given is one I can stand behind.
While there are automated ways of doing this I'm sure, and I am also interested in seeing the answers this question gets, I would recommend simply going in and moving the method definitions into different files and calling the functions normally method(param); and linking the files to your html page.
This would serve multiple purposes, including the one you are looking to acheive of breaking your code down into more manageable modules. Among those purposes also include the fact that instead of having those definitions written to memory for every instance of the object, you would only define it once and make references to it whenever you need it.
Sorry I can't be of more help without actually seeing the JavaScript File.
You can reference this stack overflow example if you need more guidance in achieving this.
You don't have to have all of the methods defined in your objects or classes, it's better to modularize these methods into different files and use the <script src="path/to/your/script.js"> </script> tags to include them all with your html/php page

Best way to structure helpers functions in NodeJS

I am trying to build a set of utils for my NodeJS project. These helpers will include: text utils (like substringing, console logging etc.), and more specific helpers like parsing the text of a tweet.
So I am trying to divide the module in different files and with a very clear idea of what each thing is meant to do.
For example I would like to achieve this:
var helpers = require("helpers");
var Utils = new helpers.Utils();
// working with text
Utils.text.cleanText("blahblalh");
// working with a tweet
Utils.twitter.parseTweet(tweet);
As you can see I am using Utils for different things, by calling very specific methods and sub methods.
I tried to understand how inheritance works here but I got a little bit lost.
This is what I am doing (some rough sample code):
//node_modules/helpers/index.js
var Text = require('./text');
var Twitter = require('./twitter');
function Utils() {
}
Utils.prototype.text = {
cleanText: function(text) {
Text.cleanText(text);
}
};
Utils.prototype.twitter = {
parseTweet(tweet) {
Twitter.parseTweet(tweet);
}
};
//node_modules/helpers/text.js
function Text() {
}
Text.prototype.cleanText = function(text) {
if (typeof text !== 'undefined') {
return text.replace(/(\r\n|\n|\r)/gm,"");
}
return null;
};
module.exports = Text;
//node_modules/helpers/twitter.js
function Twitter() {
};
Twitter.prototype.parseTweet = function(data) {
return data;
};
module.exports = Twitter
Is this a correct way? Am I doing something wrong or that could slow down the performances, etc?
To clarify how I'm understanding your post, I see two questions:
How do I structure code/methods within files, files that represent a category of utility functions
How do I organize the those categorical files into one larger library
Structuring methods within a category
Rather than making all of the category specific functions methods of objects (e.g. Twitter or Text), you could just export the functions in files named after them. Since it seems you are passing in the data you want to use, there is no need to make the functions instance methods of some empty class.
If your usage patterns of Twitter or Text usually have class variables you want to keep state on, and you want to instantiate Text or Twitter objects to use your examples, then I suppose that would be appropriate. When I setup util libs in my projects it usually is a bunch of exported functions that make up a module, rather than an exported javascript class.
To provide an example of what a text.js file made up of text-based utility functions might look like:
module.exports = {
cleanText:function(text) {
// clean it and return
},
isWithinRange(text, min, max) {
// check if text is between min and max length
}
}
Alternatively, you could do it this way:
exports.cleanText = function(text) {
// clean it and return
}
exports.isWithinRange = function (text, min, max) {
// check if text is between min and max length
}
Structuring utility category files to make a larger utility library
As far as organizing the utility methods, Luca's example is nice. I've organized some similarly like this:
utils-module/
lib/
text.js <-- this is the example file shown above
twitter.js
test/
index.js
Where index.js does something like
var textUtils = require('./lib/text');
exports.Text = textUtils;
Then when I want to use the util lib in say some User model in my node API, it's simply:
/*
* Dependencies
*/
var textUtils = require('path/to/lib').Text;
/*
* Model
*/
function User() {}
/*
* Instance Methods
*/
User.prototype.setBio = function(data) {
this.bio = textUtils.cleanText(data);
}
module.exports = User;
When I was first learning it was very helpful to look at popular, well-respected libraries to see how more experienced node/javascript devs were doing things. There are so many good (and bad) ones out there!
You can see a utils library example with lodash.
Lodash is an utility lib like underscorejs.
This library have file sustem structure like your.
It divides the functions in categories. Each category is a folder with an index.js file that includes into a namespace (literal object) each functions for that category!
Lodash/
Objects/
Function1.js
Functions2.js
....
Index.js
Array/
Function1.js
...
Index.js
Then in your code you can do this:
var objectsUtils = require("lodash/objects");
var foreach = require("lodash/array/each");
You can create a similar file system structure in order to have more flexibility.
You can require the entire lib, only one namespace or a single function.
This is better for performance, because you use only what you need and have a memory usage gain.

Indexing nodejs or browserify components with gulp

I'd like to open source (via gulp-plugin) a simple build 'indexer' I'm using in a browserify project. Basically, I'm adding an 'index.js' file into every directory inside of a glob (gulp.src). Current index.js looks like this:
var index = {};
module.exports = index;
index.assets = require('./assets');
index.build = require('./build');
index.bundler = require('./bundler');
index.component = require('./component');
index.indexer = require('./indexer');
index.server = require('./server');
index.database = require('./database');
Is this an okay way to organize a set of modules?? I'm also considering adding a node_modules folders to the top of my src dir (one level below the main dir). So instead of writing:
var form = require('./components).form; //or
var input = require('../components/forms).input
I can:
var form = require('form')
var input = require('input')
I find that this little indexer helps my workflow, maybe it'll help others too? But I don't want to put a plugin out there that's doing something potentially buggy. I asked the question to make sure that it's okay to index components like this, nested, that my syntax is correct, or if there are better ways to implement this pattern?
Sure, looks useful. You should publish it and see what feedback you get.
https://www.npmjs.com/package/file-indexer
Not a gulp plugin yet, but maybe soon?

Categories

Resources