Skip to content

Instantly share code, notes, and snippets.

View yuanchuan's full-sized avatar

Yuan Chuan yuanchuan

View GitHub Profile
var message = (function() {
var _buf = ['hello', 'hi']
, _len = _buf.length
, M = Math;
return {
get: function(){
return _buf[M.floor(M.random() * _len)] || '';
}
, add: function() {
@yuanchuan
yuanchuan / gist:1091528
Created July 19, 2011 07:01
更新并显示日志
#不想每次用TortoiseSVN 时都用鼠标右击更新
import os
import sys
def run_command(commands):
op_os = lambda x: os.system(x)
op_ms = lambda x: sys.stdout.write(x+'\n')
for cmd in commands:
@yuanchuan
yuanchuan / gist:1037937
Created June 21, 2011 14:11
代码优化尝试

今天出于好奇,读了下一款 webgame 的源代码。从整体上看,代码很简单,但也很复杂。简单是因为程序的设计思路很容易懂,除了很多全局变量以外,全是一个接一个的函数;复杂是因为每当从一个函数当中读到一个的变量名时,或是看到一个函数调用的话,总要到其它地方去找,然后再回来,加上一个函数通常都很长,冗余很多,理解起来就变得复杂了。假如让我接手这些代码的话,维护起来一定相当费劲,耦合的太紧,不容易理清楚。要是程序继续像这样下去,一不小心,就会变得跟 “意大利面条“ 一样。

这款游戏还处在开发阶段,但是想要向更大规模发展的话,以现在的程序结构来看不太容易,因为控制不了复杂性。除此之外,某些地方的性能方面也有待改进,毕竟游戏不像其它的应用程序,它的要求比较高。下面是我对一些代码的优化尝试。

避免 if else 过多

太多的 if else 看上去不够简洁优美,总是提醒你还可以写得更好。 在constant.js当中有这么两个函数:
@yuanchuan
yuanchuan / gist:998296
Created May 30, 2011 00:47 — forked from anonymous/gist:997052
在搜狐空间里自动获取最新动态
// pull.every(10);
// pull.stop();
var pull = (function(container){
var target, event, timer;
if (container) {
target = container.getElementsByTagName('a')[0];
}
@yuanchuan
yuanchuan / gist:985699
Created May 22, 2011 17:41
jQuery live('submit') and disabled submit button
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery live('submit') and disabled submit button </title>
<style>
form {margin-bottom:50px;}
</style>
</head>
function range(start, stop, step) {
var range = [];
stop || (stop = start || 0, start = 0);
step || (step = 1);
while ((step > 0 && start < stop) || (step < 0 && start > stop)) {
range.push(start);
start += step;
}
return range;
};
@yuanchuan
yuanchuan / gist:871830
Created March 16, 2011 00:58
rinting 1 to 1000 without loop or conditionals
//Printing 1 to 1000 without loop or conditionals
//http://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals/4583502#4583502
// using replace
(function(max){
new Array(max + 1).join(' ').replace(/\s/g, function(c, i){
console.log(i + 1);
})
})(1000)
@yuanchuan
yuanchuan / gist:868937
Created March 14, 2011 09:30
self-closed iframe problem
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Test -- self-closed iframe problem</title>
<script>
/* quick and dirty */
function log(info) {
return window.console
? console.log.apply(console,arguments)
@yuanchuan
yuanchuan / gist:833201
Created February 18, 2011 03:25
An interesting question
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title> An interesting question</title>
<style>
table {
border-collapse:collapse;
border-spacing:0;
margin: 100px auto 0;
function new_array(/* length */ len, /* default */ value) {
var len = ~~len;
return value
? new Array ( len + 1 ).join( value ).split( '' )
: new Array ( len );
}