Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Sunday, July 12, 2015

A memory leaking code example (for best practice with AngularJS) ?

GO HERE.
At the bottom ("Accessing the backend") let's look into the file "finance3.js".
Do you see there this line: usdToForeignRates = newUsdToForeignRates; ?
If I understood the things correctly, this is a good memory-leak, huh? Or not?

Friday, June 27, 2014

How to redirect JavaScript console.log() to Xcode's debug output

On iOS >= 7.0 it is pretty easy thanks to brilliant (and undocumented as well) framework:
@import JavaScriptCore;

...

// get UIWebView's JavaScript context
JSContext *ctx = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

// 'listen' to console.log()
ctx[@"console"][@"log"] = ^(NSString *message) { 
    NSLog(@"Javascript's console.log() :\n%@\n\n", message); 
};

Monday, July 1, 2013

Good tools that help me in my work

After writing this angry post I just have to mention really good tools and their eminent authors.

1. VIM

2. Midnight Commander

3. Firebug

4. Microsoft Visual Studio

5. ReSharper

6. XCode

7. Sublime Text

8. Bitbucket (and thanks for Git, Linus!)

9. WireShark

10. Parse

 

To be continued.

Wednesday, March 27, 2013

JavaScript sux again?

document.execCommand("delete", false.null); will be OK at least in MSIE 10
(attention to the dot between second and third PARAMETERS)

Friday, March 8, 2013

Brendan Eich about JavaScript

As is well known at this point, I created JavaScript in ten days in May 1995, under duress and conflicting management imperatives—“make it look like Java,” “make it easy for beginners,” “make it control almost everything in the Netscape browser.”
Apart from getting two big things right (first-class functions, object prototypes), my solution to the challenging requirements and crazyshort schedule was to make JavaScript extremely malleable from the start. I knew developers would have to “patch” the first few versions to fix bugs, and pioneer better approaches than what I had cobbled together in the way of built-in libraries. Where many languages restrict mutability so that, for example, built-in objects cannot be revised or extended at runtime, or standard library name bindings cannot be overridden by assignment, JavaScript allows almost complete alteration of every object.
I believe that this was a good design decision on balance. It clearly presents challenges in certain domains (e.g., safely mixing trusted and untrusted code within the browser’s security boundaries). But it was critical to support so-called monkey-patching, whereby developers edited standard objects, both to work around bugs and to retrofit emulations of future functionality into old browsers (the so-called polyfill library shim, which in American English would be called “spackle”).
Beyond these sometimes mundane uses, JavaScript’s malleability encouraged user innovation networks to form and grow along several more creative paths. Lead users created toolkit or framework libraries patterned on other languages: Prototype on Ruby, MochiKit on Python, Dojo on Java, TIBET on Smalltalk. And then the jQuery library (“New Wave JavaScript”), which seemed to me to be a relative late-comer when I first saw it in 2007, took the JavaScript world by storm by eschewing precedent in other languages while learning from older JavaScript libraries, instead hewing to the “query and do” model of the browser and simplifying it radically.
Lead users and their innovation networks thus developed a Java- Script “home style,” which is still being emulated and simplified in other libraries, and also folded into the modern web standardization efforts.
In the course of this evolution, JavaScript has remained backward (“bugward”) compatible and of course mutable by default, even with the addition of certain methods in the latest version of the ECMAScript standard for freezing objects against extension and sealing object properties against being overwritten. And JavaScript’s evolutionary journey is far from over. Just as with living languages and biological systems, change is a constant over the long term. I still cannot foresee a single “standard library” or coding style sweeping all others before it.
No language is free of quirks or is so restrictive as to dictate universal best practices, and JavaScript is far from quirk-free or restrictionist (more nearly the opposite!). Therefore to be effective, more so than is the case with most other programming languages, JavaScript developers must study and pursue good style, proper usage, and best practices. When considering what is most effective, I believe it’s crucial to avoid overreacting and building rigid or dogmatic style guides.

(c) Brendan Eich,
Foreword to "Effective JavaScript" by David Herman

Sunday, September 16, 2012

iOS UIWebView issue

When UIWebView scrolls its content, it freeze all JavaScript events until the end of scroll. So you absolutely can not programmatically observe and/or control the scrolling process like this common way:
window.onscroll = function() {
    var scrolled = window.pageYOffset || document.documentElement.scrollTop;
    // do something
}
because variable 'scrolled' will be updated only once - after the scroll is completely finished.

WinJS buggy iframe realization

Suppose we have the main page (local context) of our Metro application written in JavaScript that just holds an IFRAME (web context). We load into this iframe some web page remotely. Yes, we can control this page, it is our web site and we can edit it if we want. Well, this web page contains primitive navigation to some other pages within the same domain. OK, after clicking every navigation link the iframe's content changes, but... iframe's 'SRC' attribute - NOT (!)

No difference on RTM or on RC: the issue still exists. Cheers to Microsoft.

Sunday, July 1, 2012

How to write speedy loops in JavaScript

And if you still think that the Google Chrome's JavaScript Engine (V8, WebKit) is faster than the old good "Gecko" from Mozilla Firefox, just check the link below:

HERE IS THE TEST (nothing dangerous)

Use pure JavaScript instead of frameworks and wrappers

I hate frameworks and wrappers of any kind, because of... You must understand that any framework causes performance leaks.

Here is just one more brilliant example.

Monday, May 21, 2012

JavaScript SUX or "Gimme more shit, please!"

Shit #1

Just try this:

console.log(0.1 + 0.2 == 0.3);

Output: false (!)
Why?
Because JavaScript sux and muzdie:

console.log(0.1 + 0.2);

Output: 0.30000000000000004 (!)

Shit #2

console.log(Number.MIN_VALUE < Number.MAX_VALUE);

Output: false (!)
Why?
Because JavaScript sux and muzdie:

console.log(Number.MIN_VALUE);
console.log(Number.MAX_VALUE);

Output: 5e-324
1.7976931348623157e+308

Shit #3 (secure scope)

Object.prototype.foo = 10; 
console.log(foo); // 10

Shit #4 (happy debugging)

var a = {};
console.log(a.b === undefined); // true because property b is not set
undefined = 42;
console.log(a.b === undefined); // false

Shit #5 (are you duck?)

"string" instanceof String; // false. 
    // 'course it isn't not a string, it may look like a string
    // but actually it's masquerading as a banana.

When is a string, not a string? When it’s a duck!!!

Gimme more shit, please!

console.log(NaN === NaN); // false
console.log(Math.min() < Math.max()); // false

Etc. etc. etc...
Do you like it? Look here for more shit.

Wednesday, May 16, 2012

Project Euler, problem 1 solution

Problem 1

Stupid brute force, not masterpiece, which is generally not suitable on really large numbers. But it is easy.

JavaScript (Spider Monkey)

var num = 1000, sum = 0, res = 0;
while(num--){
    if(!(num%3) || !(num%5))
        res += num;
}
print(res);

// time: 0.02s memory: 4984 kB

Tuesday, May 15, 2012

Project Euler, problem 13 solution

Problem 13

Let's use the power of math coprocessor ;)

JavaScript (Spider Monkey)

var numbers = [
    3.7107287533902102798797998220837590246510135740250,
    4.6376937677490009712648124896970078050417018260538,
    ............... etc
    5.3503534226472524250874054075591789781264330331690
];

var sum = 0;
for(var i = numbers.length - 1; i > -1; --i) {
    sum += numbers[i];
}
var result = sum * 10000000000;
print(result.toString().substring(0,10));

// time: 0.01s memory: 4984 kB

Congratulations, the answer you gave to problem 13 is correct.
You are the 67470th person to have solved this problem.

Project Euler, problem 28 solution

Problem 28

Somebody named... Euler wrote:
"First I noted that for an n by n grid, and n being odd, the number in the top right corner is n2.
A little mathematical analysis told me that the other corners are given by: n2-n+1, n2-2n+2, and n2-3n+3.
Adding these together gives the quadratic, 4n2-6n+6.
Then all I had to do was create a loop from 3 to 1001 in steps of 2 and find the running total
(starting from 1) of the quadratic."

JavaScript (Spider Monkey)

var s = 1;
for(var n = 3; n <= 1001; n += 2) {
    s += 4 * Math.pow(n,2) - 6 * n + 6;
}
print(s);
// time: 0.02s    memory: 4984 kB

Congratulations, the answer you gave to problem 28 is correct.
You are the 39019th person to have solved this problem.

Friday, May 11, 2012

Project Euler, Problem 9 solution

Problem 9

JavaScript (SpiderMonkey)

var limit = 500,
    product = 0,
    pow_M = 0, 
    pow_N = 0;

for(var n = 3; n < limit; ++n) {
    for(var m = 4; m < limit; ++m) {
        product = m * (m + n);
        if(product == limit) {
            pow_M = Math.pow(m, 2);
            pow_N = Math.pow(n, 2);
            print((pow_M - pow_N) * (2*(m*n)) * (pow_M + pow_N));
            n = limit;
            break;
        }
    }
}

time: 0.01s memory: 4984 kB

Congratulations, the answer you gave to problem 9 is correct.
You are the 99646th person to have solved this problem.
You have earned 1 new award:
Decathlete: Solve ten consecutive problems

Tuesday, May 1, 2012

Project Euler, Problem 3 solution

Problem 3

Well...

Cheat One

Cheat Two

Cheat Three

I'm sure there is a lot of other cheats in Internet.

 

JavaScript (SpiderMonkey):

var num = 600851475143;
var ans = 0;
for(var div = 3; ; div += 2) {
    if(!(num % div)) {
        do {num /= div;} while (!(num % div));
        if(num == 1) {
            ans = div;
            break;
        }
    }
}
print(ans);

(time: 0.02s memory: 4984 kB)

Congratulations, the answer you gave to problem 3 is correct.
You are the 127054th person to have solved this problem.

UPDATED at 16 May 2012: Solution with one loop:

var num = 600851475143;
var div = 2;
while (num > 1) {
    if (0 == (num % div)) {
        num /= div;
        div--;
    }
    div++;
}
print(div);

(time: 0.02s memory: 4984 kB)

Monday, April 30, 2012

Project Euler, Problem 6 solution

Problem 6

OK, just the code without any clarifications because no one reads my blog.

JavaScript (SpiderMonkey):

var n = 100;
var sqsum = (n * (n + 1) * (2 * n + 1)) / 6;
var sumsq = (1 + n) * n / 2;
print(sumsq*sumsq - sqsum);

('n' is here just for clarity of formula)

(time: 0.02s memory: 4984 kB on usual PC)

Congratulations, the answer you gave to problem 6 is correct.
You are the 132085th person to have solved this problem.

UPDATED:
krewllobster has also offered an interesting and fast option:

var a = 0, b = 0, x = 1;
while (x < 101) {
    a += Math.pow(x,2);
    b += x;
    x += 1;
}
print(Math.pow(b,2) - a);

(time: 0.01s memory: 4984 kB)

Project Euler, Problem 16 solution

Problem 16

I like Free Software Foundation, Inc.
I like to use the right tool for the right job too.
So to get the number I typed 'bc' in the Linux command line and then '2^1000'.
Well, now I am ready to calculate the sum via JavaScript (SpiderMonkey):

 
var a="copypasted value from my command line as STRING";
var sum = 0;
for(var i = a.length - 1; i > -1; --i) sum += parseInt(a.charAt(i));
print(sum);

(time: 0.02s memory: 4984 kB on usual PC)

Congratulations, the answer you gave to problem 16 is correct.
You are the 70718th person to have solved this problem.

Project Euler, Problem 15 solution

Problem 15

"Starting in the top left corner of a 2×2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 20×20 grid?"

This problem is about permutations and so called central binomial coefficient (the binomial theorem you must remember from the school). And do you remember the Pascal's triangle? If not, check it here. (If you still don't understand what I am talking about you can see the complete solution here).
All you need is to observe that for a NxN grid there are (2n)!/(n!)2 possible ways of getting from one corner to the other one and in our case it will be 40!/(20!)2. If you are still unable to calculate it you can use A000984.
But if you still want to get the answer by yourself, do not rush to crack factorials with your lovely brute force with 350 lines of C++ code, let's start from... little cheat.
We have some ways for cheat.
Of course we could use the J language to get the central binomial coefficient:
(! +:) 20x
or even more shorter:
20!40x
but it isn't real cheat. There is a better way: http://www.google.com/search?q=40+choose+20
Bingo? Btw. tell me truth, did you know that the Google calculator has the operator 'choose'? Brilliant, isn't? You just command "40 choose 20" and Google gives you the answer: please, master! Try the same way to ask Google for money ;)


Well, now let's start thinking.

Rudy Penteado from Brazil codes in Assembler language. He discovered that:
"This is what I find 2 months ago when I solved it:
Each movement in the horizontal is a zero.
Each movement in the vertical is a one.
1st binary# in this series:
0000000000000000000011111111111111111111
last:
1111111111111111111100000000000000000000
For the numbers in between, the amount of zeros should be the same as ones.
In other words, the ones and zeros have to be rearranged."

Easy, isn't? Try to code this in Assembler.
I won't. I did my solution with some magic too:

JavaScript (Spidermonkey)

var ans = 1;
for(var c = 40, d = 1; c > 20; --c, ++d) ans = (ans * c)/d;
print(ans);

// time: 0.02s memory: 4984 kB

Congratulations, the answer you gave to problem 15 is correct.
You are the 53180th person to have solved this problem.

Sunday, April 29, 2012

Project Euler, Problem 8 solution

"Problem 8
Find the greatest product of five consecutive digits in the 1000-digit number."

Well, this problem can be solved even without computer.
Just use the best tool that you never had: your brain ;)
Use the "Find" command in your favorite text editor to highlight all 9 in the given 1000-digit number.
Is it not easy to find a combination of 99879?


But if you wanna code:

JavaScript (Spidermonkey)

var initial = [the given 1000-digit number as array of integers];
var answer = 0;
var sum = 0;
var bestsum = 0;
var tarr = [5];
for(var c = initial.length - 1; c --> 3;) {
    sum = 0;
    for(var s = c; s > c-5; --s)
        sum += initial[s];

    if(sum > bestsum) {
        bestsum = sum;
        for(var j = c, i = 4; j > c-5; --j, --i)
            tarr[i] = initial[j];
    }
}
answer = tarr[0] * tarr[1] * tarr[2] * tarr[3] * tarr[4];
print(answer);

Saturday, April 28, 2012

Factorial

( http://www.spoj.pl/problems/FCTRL/ )

C99 strict:

#include <stdio.h>
// gcc factorial.c -std=c99 -time -o factorial_c99
int zeta(int n) {
    int ret = 0;
    for(int p = 5; p <= n; p*=5)
        ret += n/p;
    return ret;
}

int main() {
    int t, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        printf("%d\n", zeta(n));
    }
    return 0;
}

JavaScript (Rhino):

ACHTUNG: this code perfectly runs at http://www.ideone.com/, but not by SPOJ lamers.

importPackage(java.io);
importPackage(java.lang);
 
var reader = new BufferedReader( new InputStreamReader(System['in']) );
var t = reader.readLine();
var num = null;

function zeta(n) {
    var ret = 0;
    for(var p = 5; p <= n; p *= 5)
        ret += parseInt(n/p);
    return ret.toString();
}

while(t--) {
    num = reader.readLine();
    if(!num)
        break;

    System.out.println( zeta(num) );
}