working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,679 snippets matching: functional

    public by micurs modified Mar 4, 2014  6865624  351  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by sTiLLiLL modified Aug 20, 2013  113670  1  5  6

    helpful snips O' javascript!

    helpful snips O' javascript!: functional js type shit
    // How to get client ip address with jQuery
    
    $.getJSON("http://jsonip.appspot.com?callback=?",function(data){
        alert( "Your ip: " + data.ip);
    });
    
    
    
    // How to parse XML with jQuery
    // file.xml:
    
    <?xml version="1.0" ?>
    <result>
        <item>
            <id>1</id>
            <title>title1</title>
            <description>desc1</description>
        </item>
        <item>
            <id>2</id>
            <title>title2</title>
            <description>desc2</description>
        </item>
        <!-- ... -->
    </result>
    
    
    $.get('file.xml',{},function(data){
        $('item',data).each(function(){
            var $this=$(this);
            var id=$this.find('id').text();
            var title=$this.find('title').text();
            var description=$this.find('description').text();
            //do something ...
        });
    });
    
    
    // How to get the number in the ids
    
    <div id="sites">
        <a id="site_1" href="http://siteA.com">siteA</a>
        <a id="site_2" href="http://siteB.com">siteB</a>
        <a id="site_3" href="http://siteB.com">siteC</a>
        ...
    </div>
    
    
    //you need to get 1 from site_1, 2 from site_2 …
    
    $("#sites a").click(function(){
        var $this     = $(this);
        var nmb     = $this.attr('id').match(/site_(\d+)/)[1];
        ...
    });
    
    
    // How to transform a number like 12343778 into 12.343.778
    
    <div id="result">12343778</div>
    
    var delimiter = '.';
    $('#result').html()
                .toString()
                .replace(new RegExp("(^\\d{"+($this.html().toString().length%3||-1)+"})(?=\\d{3})"),"$1" + delimiter).replace(/(\d{3})(?=\d)/g,"$1" + delimiter);
    
    
    // Count number of textarea lines
    
    var text = $("#textareaId").val();
    var lines = text.split(/\r|\r\n|\n/);
    alert(lines.length);
    
    
    // Logging to the firebug console
    
    jQuery.fn.log = function (msg) {
        console.log("%s: %o", msg, this);
        return this;
    };
    $('#some_div').find('li.source>input:checkbox').log("sources to uncheck").removeAttr("checked");
    
    
    // Find X/Y of an HTML element with Javascript
    
    var getCumulativeOffset = function (obj) {
        var left, top;
        left = top = 0;
        if (obj.offsetParent) {
            do {
                left += obj.offsetLeft;
                top  += obj.offsetTop;
            } while (obj = obj.offsetParent);
        }
        return {
            x : left,
            y : top
        };
    };
    
    
    // Validate Credit Card
    
    function isCreditCard( CC ){
        if (CC.length > 19)
            return (false);
     
        sum = 0; mul = 1; l = CC.length;
        for (i = 0; i < l; i++){
            digit = CC.substring(l-i-1,l-i);
            tproduct = parseInt(digit ,10)*mul;
            if (tproduct >= 10)
                sum += (tproduct % 10) + 1;
            else
                sum += tproduct;
            if (mul == 1)
                mul++;
            else
                mul–;
        }
        if ((sum % 10) == 0)
            return (true);
        else
            return (false);
    }
    
    
    // Distinguish left and right mouse click
    
    $("#element").live('click', function(e) {
        if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
            alert("Left Button");
        }
        else if(e.button == 2)
            alert("Right Button");
    });
    
    
    //How to get the native image size
    
    var img = $('#imageid');
    var theImage = new Image();
    theImage.src = img.attr("src");
    alert("Width: " + theImage.width);
    alert("Height: " + theImage.height);
    PREVIOUS:
    
    

    public by micurs modified Sep 23, 2014  12167  4  10  4

    Typescript + underscore: serializing objects

    This little example runs on node.js and assumes you have the typescript type-definition file in the types subdirectory. The example defines two classes one representing a undergrad course in computer science and another one representing possible students for the course. Few things are interesting here: 1 - the overloading of the toString()
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    function write(msg) {
        process.stdout.write(msg+'\n');
    }
    
    class Student {
      firstName : string;
      lastName : string;
    
      constructor( n: string, v: string ) {
        this.firstName = n;
        this.lastName = v;
      }
    
      toString() : string {
        return '[ ' + this.firstName + ' ' + this.lastName + ' ]';
      }
    }
    
    class Class {
      title : string = "Computer Science 101";
      participants : Student[] = new Array();
    
      addStudent( s : Student ) : any {
        this.participants.push(s);
      }
    
      toString() : string {
        return this.title + '\n\t' 
              + _.reduce( this.participants, (acc,s) => acc += '\n\t'+ s );
      }
    
    }
    
    var firstSemesterClass : Class = new Class();
    
    firstSemesterClass.addStudent( new Student("John","Smith"));
    firstSemesterClass.addStudent( new Student("Frank","Gehry"));
    
    write( firstSemesterClass );
    
        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  3545  4  8  25

    Enumerator.js... behind every enumeration you'll find a good Iterator. I guess.... LoL

    the future is now!
    // slick as snot Enumerable type!!!! yeah!
    
    var Enum = {
          create: function (collection) {
            var index=0;
            return {
              next: function() {
                if (index < collection.length) {
                  return ({ value: collection[index++], done: false });
                }
                else {
                  return ({ value: null, done: true});
                }
             }
          };
       }
    };
    
    // use it like this... (strings, bool, numbers, all gewd!)
    
    var arr=['rtJKvE', '!!@wrh', 433, 'yippe', 216,'PRdUrg', 3038, 'whaa?'],
      it = Enumerator.create(arr),
      primer = 0;
    
    while(primer !== null) {
      primer = it.next().value;
    	document.writeLine(primer);
    }
                

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  4697  3  7  16

    kwik dirty arraySort....

    kwik example of a complex array sort
    // sort a complex array
    
    var mehAry = [{id: 140, name: "abc", age: "twenty"},
                  {id: 62009, name: "def", age: "thirty"},
                  {id: 3030, name: "ghi", age: "forty" },
                  {id: 455, name: "jkl", age: "fifty" }];
          
    function complexSort (itm1, itm2) {
        var a = itm1.id, b = itm2.id;
        return (a - b);
    }
    
    var sortedArray = mehAry.sort(complexSort);  
    
    //  sortedArray = [{id: 140, name: "abc", age: "twenty"},{id: 455, name: "jkl", age: "fifty" },
    //                 {id: 62009, name: "def", age: "thirty"},{id: 3030, name: "ghi", age: "forty" }];                        

    public by sTiLL-iLL @ SniPitz-KND modified Oct 13, 2014  3744  3  7  19

    Equality in javascript...

    An "equals" method for any type... try it, you might like it
    
    // a true Equalty comparor in JS
    
    Object.prototype.equals = function(x) {
        var p;
        for(p in this) {
          if (typeof(x[p]) == "undefined") {
            return false;
          }
        }
        for(p in this) {
          if (this[p]) {
            switch(typeof(this[p])) {
              case "object":
                if (!this[p].equals(x[p])) {
                  return false;
                }
                break;
              case "function":
                if (typeof(x[p]) == "undefined"||(p != "equals" &&
                  this[p].toString() != x[p].toString())) {
                    return false;
                }
                break;
              default:
                if (this[p] != x[p]) {
                  return false;
                }
            }
          }
          else {
            if (x[p]) {
              return false;
            }
        }
        for(p in x) {
          if(typeof(this[p])=="undefined") {
            return false;
          }
        }
        return true;
      }
    }
    

    public by micurs modified Feb 23, 2014  3710  2  7  3

    Generate comma separated value string in Typescript using underscore _.reduce()

    Underscore work well with Typescript lambda syntax.
    import _ = require("underscore");
    
    var values: number[] = [ 5, 19, 64, 12, 45 ];
    
    var csv: string = 
     _.reduce( values, 
              ( acc: string, item ) => acc+= ','+item.toString() 
             );
         

    public by sTiLL-iLL @ SniPitz-KND modified Oct 4, 2014  2856  7  8  21

    ... it's KliKQ.js & its meh family brah......

    Functional and flexible Collection or group - type data-structure. Itsupports gets, sets, sorts, all kindz of shit. Try it just once and the Government says your as gewd as hooked for life!
    
    var KliKQ = (function () {
        
    	function KliKQ() {
    		this.mehArry = [];
    		this.dahMap = {};
    		this.length = 0;
    	}
    	
    	KliKQ.prototype.keyRoster = function () {
    		var kz = [];
    		
    		this.eachIn(function (val, k) {
    			kz.push(k);
    		});
    		
    		return kz;
    	};
    	
    	
        KliKQ.prototype.keyAssign = function (k, obj) {
    		if (obj === 'undefined') {
    			this.keyRemove(k);
    		} 
    		else if (!this.dahMap.hasOwnProperty(k)) {
    			
    			this.dahMap[k] = this.mehArry.length;
    			
    			this.mehArry.push({
    				value: obj,
    				key: k
    			});
    			
    			this.length++;
    		} 
    		else {
    			this.mehArry[this.dahMap[k]].value = obj;
    		}
    	};
    	
    	
        KliKQ.prototype.keyPull = function (k) {
    		if (this.dahMap.hasOwnProperty(k)) {
    			return this.mehArry[this.dahMap[k]].value;
    		}
    		
    		return undefined;
    	};
    	
    	
    	KliKQ.prototype.idxGet = function (idx) {
    		if (this.length <= idx) {
    			return undefined;
    		}
    		
    		return this.mehArry[idx].value;
    	};
    	
    	
        KliKQ.prototype.keyRemove = function (k) {	
    		if (this.dahMap.hasOwnProperty(k)) {
    			
    			var idx = this.dahMap[k], nam = "";
    			delete this.dahMap[k];
    			
    			for (nam in this.dahMap) {
    				if (this.dahMap.hasOwnProperty(nam) && this.dahMap[nam] >= idx) {
    					this.dahMap[nam]--;
    				}
    			}
    			
    			this.mehArry.splice(idx, 1);
    			this.length--;
    		}
    	};
    	
    	
    	KliKQ.prototype.eachIn = function (cback, slf) {
    		var i = 0, ary = this.mehArry, len = ary.length;
    		
    		if (!slf) {
    			slf = this;
    		}
    		
    		while (i < len) {	
    		    if (ary[i].value !== 'undefined') {
    				cback.call(slf, ary[i].value, i, ary[i].key, this);
    			}
    			
    		    i++;
    		}
    	};
    	
    	function kmprItems(dis, dat) {
    		return (dis == dat) ? 0 : (dis < dat) ? -1 : 1;
    	};
    	
    	KliKQ.prototype.keySort = function (xprsn) {
    		var i = 0, ary = this.mehArry, len = ary.length;
    		
    		if (!xprsn) {
    			xprsn = kmprItems;
    		}
    		
    		this.mehArry.sort(function (dis, dat) {
    			return xprsn(dis.key, dat.key);
    		});
    		
    		while (i < len) {
    			this.dahMap[ary[i].key] = i;
    			i++;
    		}
        };
    	
    	return KliKQ;
    	
    }());

    public by sTiLL-iLL modified Dec 1, 2015  2113  2  7  27

    Parallyzed.js.....never move again,.... or do....

    .... my pattern for concurrant, Parallel Xekution....sick asyncro stuff!
    // my pattern for executing a full-on parrallel series of async tasks!
    
    function Parallyzed(cBakLst, last) {
      var rzlts = [], cnt = 0;
      cBakLst.forEach(function(step, idx) {
        step(function() {
          rzlts[idx] = Array.prototype.slice.call(arguments);
          cnt++;
          if(cnt == cBakLst.length) {
            last(rzlts);
          }
        });
      });
    }
    
    var taskList = [];
    
    function myAsyncTask1(argz, step) {
      var compRZLT = Math.floor(Math.random() * 5 + 1) * 100;
      console.log('task with \''+argz+'\', return in '+compRZLT+' ms');
      setTimeout(function() {
        step(argz * 2);
      }, compRZLT);
    }
    
    taskList.push(myAsyncTask1);
    
    function myAsyncTask2(url, cBak) {
    	var xhr = new XMLHttpRequest();
    	xhr.open('GET', url, true);
    	xhr.responseType = 'JSON';
    	xhr.onload = function () {
    	if (this.status == 200) {
    			var lst = JSON.parse(xhr.responseText);
    			console.log("paths retreived... ");
    		}
    		cBak(lst);
    	};
    	xhr.send({});
    }
    
    taskList.push(myAsyncTask2);
    
    function myAsyncTask3(lst, xp, s, cBak) {
    	lst.forEach(function (itm) {
    		var mp = document.createElement('li');
    		mp.innerHTML = "<a href='#'>" + itm + "</a>";
    		mp.onclick = wenKlik;
    		xp.appendChild(mp);
    	});
    	s.appendChild(xp);
    	cBak(s);
    }
    
    taskList.push(myAsyncTask3);
    
    function myAsyncTask4(argz, step) {
      var compRZLT = Math.floor(Math.random() * 5 + 1) * 100;
      console.log('task with \''+argz+'\', return in '+compRZLT+' ms');
      setTimeout(function() {
        step(arg * 2);
      }, compRZLT);
    }
    
    taskList.push(myAsyncTask4);
    
    function myAsyncTask5(url, argz, step, cBak) {
    	var xhr = new XMLHttpRequest();
    	xhr.open('POST', url, true);
    	xhr.responseType = 'JSON';
    	xhr.onload = function () {
    	if (this.status == 200) {
    			var rzlt = JSON.parse(xhr.responseText);
    		}
    		step(cBak(rxlt));
    	};
    	xhr.send(argz);
    }
    
    taskList.push(myAsyncTask5);
    
    function lastOne(rzlts) {
      console.log('finished!', rzlts);
    }
    
    
    Parallyzed(taskList, lastOne);
    
                            

    public by sTiLL-iLL modified Oct 3, 2014  3619  4  8  18

    map, reduce, flter..... MY WAY

    funky functions that operate iteratively against an array or something similar
    // Map Reduce & Filter fo ya!
    
    function map(func, array) {
    
        var len = array.length;
    
        var result = new Array(len);
    
        for (var i = 0; i < len; i++)
    
            result[i] = func(array[i]);
    
        return result;
    
    }
    
    
    
    function reduce(func, start, array) {
    
        var len = array.length;
    
        for (var i = 0; i < len; i++)
    
            start = func(start, array[i]);
    
        return start;
    
    }
    
    
    
    function filter(test, array) {
    
        var result = [],
    
            len = array.length;
    
        for (var i = 0; i < len; i++) {
    
            var current = array[i];
    
            if (test(current))
    
                result.push(current);
    
        }
    
        return result;
    
    }
    • Public Snippets
    • Channels Snippets