Rewrite following piece of javascript code - javascript

I am trying to create a function that mimics Array.prototype.push.
It takes a variable number of arguments and pushes them into a specific array.
I have managed to do this with the following code:
var array=[];
function append(){
for(var i=0;i<arguments.length;i++)
array.push(arguments[i]);
}
Now my question is:Can I rewrite the append function without using "for loop"?
Thanks in advance.

If you need to get arguments array, you should use Array's slice function on an arguments object, and it will convert it into a standard JavaScript array:
var array = Array.prototype.slice.call(arguments);

You could use Array.prototype.push.apply
function append(){
// make arguments an array
var args = Array.prototype.slice.call(arguments);
// return the number of elements pushed in the array
return Array.prototype.push.apply(array, args);
}
So, what's happening here with args? We use Array.prototype.slice.call with arguments, the purpose being to make arguments an array, because it is a special object. Function.prototype.call is used to call a function with a specific context (aka this), and then the arguments to call the function with (comma separated). Conveniently, it appears that slice() looks at the length property of the this context, and arguments has one too, and when not empty, has properties from 0 to length -1, which allows slice to copy arguments in a new array.

You can rewrite this without a for loop, but you have to use a loop of some sort (you're working with multiple items, it's a necessity).
If you have access to ES6 or Babel, I would use something like:
function append(...args) {
return array.concat(args);
}
Without ES6, you need to work around the fact that arguments isn't a real array. You can still apply most of the array methods to it, by accessing them through the Array prototype. Converting arguments into an array is easy enough, then you can concat the two:
function append() {
var args = Array.prototype.map.call(arguments, function (it) {
return it;
});
return array.concat(args);
}
Bear in mind that neither of these will modify the global array, but will return a new array with the combined values that can be used on its own or assigned back to array. This is somewhat easier and more robust than trying to work with push, if you're willing to array = append(...).

Actually i honestly believe that push must be redefined for the functional JS since it's returning value is the length of the resulting array and it's most of the time useless. Such as when it's needed to push a value and pass an array as a parameter to a function you cant do it inline and things get messy. Instead i would like it to return a reference to the array it's called upon or even a new array from where i can get the length information anyway. My new push proposal would be as follows;
Array.prototype.push = function(...args) {
return args.reduce(function(p,c) {
p[p.length] = c;
return p
}, this)
};
It returns a perfect reference to the array it's called upon.

Related

Question about delay function source code [duplicate]

I know it is used to make arguments a real Array, but I don‘t understand what happens when using Array.prototype.slice.call(arguments);.
What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
How is this in the .slice() function an Array? Because when you do:
object.method();
...the object automatically becomes the value of this in the method(). So with:
[1,2,3].slice()
...the [1,2,3] Array is set as the value of this in .slice().
But what if you could substitute something else as the this value? As long as whatever you substitute has a numeric .length property, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.
The .call() and .apply() methods let you manually set the value of this in a function. So if we set the value of this in .slice() to an array-like object, .slice() will just assume it's working with an Array, and will do its thing.
Take this plain object as an example.
var my_object = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
length: 5
};
This is obviously not an Array, but if you can set it as the this value of .slice(), then it will just work, because it looks enough like an Array for .slice() to work properly.
var sliced = Array.prototype.slice.call( my_object, 3 );
Example: http://jsfiddle.net/wSvkv/
As you can see in the console, the result is what we expect:
['three','four'];
So this is what happens when you set an arguments object as the this value of .slice(). Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as if it were working on a real Array.
The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.
Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.
So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call() or [].slice.call(), we just get it straight from the prototype. This is so we don't have to initialise a new array.
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.
Normally, calling
var b = a.slice();
will copy the array a into b. However, we can’t do
var a = arguments.slice();
because arguments doesn’t have slice as a method (it’s not a real array).
Array.prototype.slice is the slice function for arrays. .call runs this slice function, with the this value set to arguments.
Array.prototype.slice.call(arguments) is the old-fashioned way to convert an arguments into an array.
In ECMAScript 2015, you can use Array.from or the spread operator:
let args = Array.from(arguments);
let args = [...arguments];
First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:
Array.prototype.slice extracts the slice method from Array's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined.
The call() method allows you to specify a method's context, basically making these two calls equivalent:
someObject.slice(1, 2);
slice.call(someObject, 1, 2);
Except the former requires the slice method to exist in someObject's prototype chain (as it does for Array), whereas the latter allows the context (someObject) to be manually passed to the method.
Also, the latter is short for:
var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);
Which is the same as:
Array.prototype.slice.call(someObject, 1, 2);
// We can apply `slice` from `Array.prototype`:
Array.prototype.slice.call([]); //-> []
// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true
// … we can just invoke it directly:
[].slice(); //-> []
// `arguments` has no `slice` method
'slice' in arguments; //-> false
// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]
// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]
Its because, as MDN notes
The arguments object is not an array. It is similar to an array, but
does not have any array properties except length. For example, it does
not have the pop method. However it can be converted to a real array:
Here we are calling slice on the native object Array and not on its implementation and thats why the extra .prototype
var args = Array.prototype.slice.call(arguments);
Dont forget, that a low-level basics of this behaviour is the type-casting that integrated in JS-engine entirely.
Slice just takes object (thanks to existing arguments.length property) and returns array-object casted after doing all operations on that.
The same logics you can test if you try to treat String-method with an INT-value:
String.prototype.bold.call(11); // returns "<b>11</b>"
And that explains statement above.
Array.prototype.slice=function(start,end){
let res=[];
start=start||0;
end=end||this.length
for(let i=start;i<end;i++){
res.push(this[i])
}
return res;
}
when you do:
Array.prototype.slice.call(arguments)
arguments becomes the value of this in slice ,and then slice returns an array
It uses the slice method arrays have and calls it with its this being the arguments object. This means it calls it as if you did arguments.slice() assuming arguments had such a method.
Creating a slice without any arguments will simply take all elements - so it simply copies the elements from arguments to an array.
Let's assume you have: function.apply(thisArg, argArray )
The apply method invokes a function, passing in the object that will be bound to this
and an optional array of arguments.
The slice() method selects a part of an array, and returns the new array.
So when you call Array.prototype.slice.apply(arguments, [0]) the array slice method is invoked (bind) on arguments.
when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
Maybe a bit late, but the answer to all of this mess is that call() is used in JS for inheritance.
If we compare this to Python or PHP, for example, call is used respectively as super().init() or parent::_construct().
This is an example of its usage that clarifies all:
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
/*
arguments: get all args data include Length .
slice : clone Array
call: Convert Object which include Length to Array
Array.prototype.slice.call(arguments):
1. Convert arguments to Array
2. Clone Array arguments
*/
//normal
function abc1(a,b,c){
console.log(a);
}
//argument
function: function abc2(){
console.log(Array.prototype.slice.call(arguments,0,1))
}
abc1('a','b','c');
//a
abc2('a','b','c');
//a

Comparison between normal array vs generated by back-tick array

I am creating an array by two way.
my first way is creating an array normally
my second way is creating an array by using backticks function
let array=["1234"];
function createArrayByBakticks(obj)
{
return obj;
}
let backtickArray = createArrayByBakticks `1234`;// it's responding an array
console.log(array); //1st way and it returns an array
console.log(backtickArray ); //2nd way and it returns a same array
backtickArray.push(1);// but it's throwing an error while push a new value.
// Error: Uncaught TypeError: Cannot add property 1, object is not extensible
console.log(backtickArray);
Above both ways are return as a array data. But the second array is not supporting inbuilt function of array which is generated by back-ticks. WHY? And what is the difference between in the both ways?
createArrayByBakticks is used as a so-called tag function. The first argument passed to the function is an array containing all strings of the template literal.
If you dive deep into the language specification, section 12.2.9.3, then you will see the following step is performed after the array has been created:
Perform SetIntegrityLevel(template, "frozen").
This means that in your case objis frozen and no property can be added. That's why invoking push doesn't work.
You can confirm this by calling console.log(Object.isFrozen(backtickArray)).
The array returns from the function by value, meaning it's immutable.
If you use concat, you'll get a new copy of it, which you can modify:
let array = ["1234"];
function createArrayByBakticks(obj) {
return obj;
}
let backtickArray = createArrayByBakticks `1234`; // it's responding an array
console.log(array); //1st way and it returns an array
console.log(backtickArray); //2nd way and it returns a same array
let newArray = backtickArray.concat(1); // a new mutable array is generated
newArray.push(2); // so you can even keep modifying it
console.log(newArray);

How to manipulate a JavaScript array passed to a function without changing the original argument array?

I would like to work with an array passed to a function while leaving the original array untouched. Here is a simple example of the problem.
function whyDoesArrChange(arr) {
var newArr = arr;
newArr.push(4);
return arr;
}
console.log(whyDoesArrChange([1,2,3]));
// OUT: [1,2,3,4]
I would like only newArr to be changed, but the arr (from the arguments) returns the pushed value as well (returns [1,2,3,4]). How can I avoid this?
When passing an array to a function, the value of that array is a reference, you have to clone it to break the reference.
There are multiple ways to achieve this:
1 - Using .slice();
var newArr = arr.slice();
2 - Using .concat
var newArr = arr.concat([]);
3 - Using JSON.parse & JSON.stringify
var newArr = JSON.parse(JSON.stringify(arr));
You can check more ways and see how they perform in this jsperf I found.
While Marcos' answer is correct, no doubt. There are more pure Array functions that can be used (A pure function is a function that doesn't alter data outside of its' scope).
Usually, if you'd like to do multiple actions on the array, I would go with Marcos' answer and then do those changes as usual. But when that's not the case, the following information may be useful:
Adding: arr.concat([1]);
Subarray (i to j): arr.slice(i, j + 1);
Removing (i to j): arr.slice(0, i).concat(arr.slice(j + 1));
Also, filter and map are pure function that will not alter the array.
In JavaScript, when you use (=) to assign a value from a variable to another one, you're just passing the entire variable, so each time one or another changes, the other will change too.
According to your question, the best way that works for me is using the native .slice() JavaScript method to the arrays object. For your code:
function whyDoesArrChange(arr) {
var newArr = arr.slice();
newArr.push(4);
return arr;
}
Because reference types (arrays and objects) can get modified inside functions when passed as arguments, while primitive types (numbers, strings, booleans etc.) don't.
You can make a shallow copy the array with .slice() and work on that array, or return a new array with the .concat method.
function whyDoesArrChange(arr) {
return arr.concat(4);
}

Better way to concat function arguments with an extra value

I've the following situation: I want to prepend (unshift) the arguments given to an function by another parameter. How my current approach looks like:
function eventReferer(event) {
var self = this;
return function() {
var args = ([event]).concat(Array.prototype.slice.call(arguments, 0, arguments.length));
return eventFunction.apply(self, args);
};
}
"eventFunction" is a custom function. I need to redirect the called event + all arguments to this function.
Because "arguments" is no valid Array in Javascript, the method of Array will not work. Is there any better way to merge my event and the arguments to a new array?
There are some more ways shown in the benchmark on http://jsperf.com/ghel-args - The only thing that's to do, is to unshift the "event" param to the array after converting the arguments to a regular JS-Array using one of the functions. So my first approach was correct, but not ideal (because it's not the fastest method available).

Creating multi-dimensional arrays in javascript, error in custom function

I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";

Categories