- use simple iteration
split()
vsjoin()
- array vs string
- use simple recurtion
function factorial(n){
return n === 0 ? 1 : n * factorial(n - 1);
}
- use simple iteration
function factorial(n){
var res = 1;
for (var i = 1; i < n; i++) res *= i;
return res;
}
- can use
Array.filter()
, usearguments
Arguments object: 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.
- impl
function removeFromArray(arr) {
var argsToRemove = [].slice.call(arguments, 1);
return arr.filter(function(d) {
return argsToRemove.indexOf(d) === -1;
});
}
//OR
function removeFromArray(arr) {
var argsToRemove = [].slice.call(arguments, 1);
return arr.filter( (d) => !argsToRemove.includes(d) );
});
}
- write a test for this!
expect(removeFromArray([])).toEqual([]);
expect(removeFromArray([], 1)).toEqual([]);
expect(removeFromArray([1])).toEqual([1]);
expect(removeFromArray([1], 1)).toEqual([]);
expect(removeFromArray([1, 2], 1)).toEqual([2]);
expect(removeFromArray([1, 2], 2, 3)).toEqual([1]);
...
- output:
5 5 5 5 5
- javascript closures
- fix it!
for (var i = 0; i < 5; i++) {
(function(n){
setTimeout(function() { console.log(n); }, n * 1000 );
})(i);
}
- output:
undefined function undefined
- hoisting
- function decleration vs function expression (
foo is not a function
)
- output:
1 4 3 2
- event loop
- implement
setTimeoutSync()
function delay(ms) {
var now = Date.now();
while(Date.now() < now + ms){
/* do nothing */
}
}
function setTimeoutSync(cb, ms) {
delay(ms);
cb();
}
- or use es6
await
function foo(){}
foo();
foo.call();
foo.apply();
foo.bind()();
var x = {};
x.f = foo;
x.f();
-
prototype
- module patter, use
prototype
function Point(x, y) { this.x = x; this.y = y; } function Shape(point){ this.center = point; } Shape.prototype.draw = function(){ console.log(this.center); }; Shape.prototype.move = function(point){ this.center = point; };
- with private (wha't the cost?)
var Shape = (function() { function Shape(point) { var center = point; this.draw = function() { console.log(center); }; this.move = function(point) { center = point; }; } return Shape; })();
- inheritance
function Rect(){} Rect.prototype = new Shape(); var rect1 = new Rect(); //OR var rect2 = Object.create(Shape);
- module patter, use
- use vanila javascript (xhr, addEventListener)
- use
e.stopPropagation()
- DOM vs global
- use
e.preventDefault()
- reference a dom element
-
float: left
-
margin
,padding
andborder
-
solution
- html
<div class="content"> </div> <div class="modal-bkg"> <div class="modal"> hello world </div> </div>
- css
.modal-bkg { position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 1000; background: rgba(0, 0, 0, 0.5); cursor: not-allowed; } .modal { position: relative; top: calc((50% - 50px) / 2); left: calc((50% - 50px) / 2); height: 50px; width: 50px; background: white; cursor: pointer; }
-
why not use
opacity
?