-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyUnshift.html
More file actions
83 lines (73 loc) · 2.7 KB
/
myUnshift.html
File metadata and controls
83 lines (73 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<script src="..\my-jsArrayMethods\simpletest.js"></script>
<script>
// The unshift() method adds one or more elements to the beginning of an array.
// It returns the new length of the array.
// The unshift method inserts the given values to the beginning of an array-like object.
// unshift is intentionally generic;
// this method can be called or applied to objects resembling arrays.
// unshift may not work on an object that does not contain a length property that is a number.
// Parameters:
// elementN: The elements to add to the front of the array.
// Return Value:
// the new length of the appended array.
// Notes:
// this version of unshift will overwrite the native prototype Array.prototype.unshift.
Array.prototype.unshift = function(elements) {
var newLength = this.length + arguments.length;
var updatedObj = this;
var temp;
if (Array.isArray(this)) {
temp = [];
} else {
// handle an array-like object.
temp = {};
if (typeof this === 'object') {
if (!this.length) {
this.length = 0;
}
}
}
// store data from 'this' on temp variable.
for (var i = 0; i < this.length; i++) {
temp[i] = this[i];
}
// append the arguments to the called upon array or array-like object.
for (var i = 0; i < newLength; i++) {
if (i < arguments.length) {
this[i] = arguments[i];
} else {
this[i] = temp[i - arguments.length];
}
if (!Array.isArray(this)) {
this.length ++;
}
}
return this.length;
}
tests({
'1. If passed no arguments, it should return the length of the array it is called upon.': function() {
var myArray = [];
var unshifted = myArray.unshift();
eq(unshifted, 0);
},
'2. It should prepend all elements to the array it is called upon.': function() {
var myArray = ['a thing'];
var unshifted = myArray.unshift('prepended thing');
eq(myArray[0], 'prepended thing');
eq(myArray[1], 'a thing');
eq(unshifted, 2);
},
'3. It should create a length property equal to zero if applied or called without any arguments to an array-like object without a length property.': function() {
var myObj = {};
Array.prototype.unshift.call(myObj);
eq(myObj.length, 0);
},
'4. It should shift elements onto an array-like object.': function() {
var myObj = {length: 0};
Array.prototype.unshift.call(myObj, 'first item', 'second item');
eq(myObj.length, 2);
eq(myObj[0], 'first item');
eq(myObj[1], 'second item');
},
})
</script>