• Stars
    star
    343
  • Rank 123,371 (Top 3 %)
  • Language
    CoffeeScript
  • Created over 11 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎓 JavaScript Patterns snippets for Sublime Text

JavaScript Patterns snippets Downloads per month

JS Patterns logo

Snippets for Sublime Text with good solutions for regular problems in JavaScript.

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

– Wikipedia

To install through Package Control, search for JavaScript Patterns. If you still don't have Package Control in Sublime Text, go get it. If you insist to not install it, you can download the package and put it manually inside your Pacakages directory. It should work but will not update automatically.

Snippets

Some JS Patterns snippets in the wild.

Preview

Immediate function

trigger: ifun⇥

To keep the global scope clean and to use strict mode in a controlled enviroment, without triggering it in the global scope.

;(function() {
    'use strict';
    // closure scope
}());

Reference:

For in

trigger: forin⇥

For-in loops in JavaScript will iterate over new properties added to the prototype chain of the object we are iterating. To loop through only in the object's properties, we have to use .hasOwnProperty('propertyName'). Like below.

for (var prop in obj) {
  if ({}.hasOwnProperty.call(obj, prop)) {
    obj[prop];
  }
}

Reference:

Object.keys loop

trigger: okl⇥

If your enviroment supports that method, prefer this over for in.

Object.keys(obj).forEach(function(key) {
  // inside loop
});

Improved for loop

trigger: ifor⇥

A faster way to write a for loop. It caches the array size, so we don't need to recalculate the size at every iteration.

for (i = 0, len = arr.length; i < len; i++) {
  // array length is calculated only 1 time and then stored
}

Reference:

Constructor pattern

trigger: constructor⇥

That constructor pattern enforces the use of new, even if you call the constructor like a function. In JavaScript, if the new keyword is forgotten, this will reference the global object inside the constructor, and that's never a desirable situation.

That approach is like $() and $.Deferred() in jQuery, where you can call it in the same way with new $() and new $.Deferred.

var ConstructorName = (function() {
  'use strict';

  function ConstructorName(arg1, arg2) {
    // enforces new
    if (!(this instanceof ConstructorName)) {
        return new ConstructorName();
    }

    // constructor body
  }

  ConstructorName.prototype.someMethod = function(arg) {
    // method body
  }

  return ConstructorName;
}());

Reference:

Singleton pattern

trigger: singleton⇥

With the Singleton pattern there will be only one instance of a constructor function. If you try to instantiate another one, the first instance that was created at first will be returned.

var singletonName = (function() {
  'use strict';

  var instance;

  singletonName = function() {
    if (instance) {
      return instance;
    }

    instance = this;

    // your code goes here
  };

  return singletonName;
}());

Reference:

Module

trigger: module⇥

A simple module pattern. Uses strict mode and suggest the use of a init function for kickoff. Also possible to define some "private" methods and variables. Only the variable with the module's name is returned and therefore made public outside the closure.

var moduleName = (function() {
  'use strict';

  var privateVar = '';

  var moduleName = {
    init: {
      // kickoff
    }
  }

  return moduleName;
}());

Reference:

Revealing module

trigger: rmodule⇥

Some might say it's a less verbose and more organized way to define a module. It declares all the variables and functions in the private scope and returns an object with references to what is going to be public.

var revealingModule = (function() {
  'use strict';

  var privateVar = 'foo';
  var publicVar = 'bar';

  function privateFunction() {

  }

  function publicFunction() {

  }

  return {
    publicVar: publicVar,
    publicFunction: publicFunction
  };
}());

AMD

trigger: amdmod⇥

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded. This is particularly well suited for the browser environment where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems.

define([
    "module1"
], function(module1) {
    "use strict";

    // static public property
    myModule.prop;

    var myModule = function() {

        // public var
        this.b = null;

        // pseudo-protected var
        this._c = null;

    };

    function privateMethod(args) {
    };

    myModule.staticMethod = function(args) {
    };

    myModule.prototype.publicMethod = function(args) {
    };

    return myModule;
});

Reference:

Memoization

Caches the return value of function. Useful for repetitive calls for a computationally expensive function.

var expensiveFunction = (function() {
  'use strict';

  var funcMemoized = function() {
    var cacheKey = JSON.stringify(Array.prototype.slice.call(arguments));
    var result;

    if (!funcMemoized.cache.hasOwnProperty(cacheKey)) {
        // your expensive computation goes here

        funcMemoized.cache[cacheKey] = result;
    }

    return funcMemoized.cache[cacheKey];
  }

  funcMemoized.cache = {};

  return funcMemoized;
}());

Throttle

The function will be called no more than one time every X seconds, even if you call it repeatedly. Useful for some DOM events like the resize event on the window.

var onResize = (function() {
  'use strict';

  var timeWindow = 200; // time in ms
  var lastExecution = new Date((new Date()).getTime() - timeWindow);

  var onResize = function(args) {
    // your code goes here
  };

  return function() {
    if ((lastExecution.getTime() + timeWindow) <= (new Date()).getTime()) {
      lastExecution = new Date();
      return onResize.apply(this, arguments);
    }
  };
}());

Reference:

Debounce

The function will postpone its execution until X miliseconds have elapsed since the last call. Useful for some events that you want to happen after some time after the last interaction, like an autocomplete or a double-click in a submit button.

var autocomplete = (function() {
  'use strict';

  var timeWindow = 500; // time in ms
  var timeout;

  var autocomplete = function(arg1, arg2) {
    // your code goes here
  };

  return function() {
    var context = this;
    var args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      autocomplete.apply(context, args);
    }, timeWindow);
  };
}());

Reference:

Namespace

trigger: namespace⇥

Namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They're also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified. Extensibility is of course key to any scalable namespacing pattern and IIFEs can be used to achieve this quite easily.

;(function(namespace) {
  'use strict';

  // your code goes here
  // namespace.method = function(){};
})(window.namespace = window.namespace || {});

Reference:

Once

trigger: once⇥

Creates a function that can only be executed one time.

var once = (function() {
  var didRun = false;

  // This function will be executed only once, no matter how many times
  // it is called.
  function once() {
    // ...
  }

  return function() {
    if (didRun) {
      return;
    }

    didRun = true;

    return foo.apply(this, arguments);
  }
})();

Contributors

59  Caio Gondim
01  Arne Schlüter
01  Breno Calazans
01  Philip Blyth
01  gaboesquivel

Donating

If you found this project useful and are willing to donate, transfer some bitcoins to 1BqqKiZA8Tq43CdukdBEwCdDD42jxuX9UY or through the URL https://www.coinbase.com/caiogondim

Or via PayPal.me https://www.paypal.me/caiogondim.

License

The MIT License (MIT)

Copyright (c) 2014 Caio Gondim

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

bullet-train.zsh

🚄 An oh-my-zsh shell theme based on the Powerline Vim plugin
Makefile
2,822
star
2

fast-memoize.js

🐇 Fastest possible memoization library
JavaScript
2,578
star
3

logdown.js

✏️ Debug utility with markdown support that runs on browser and server
JavaScript
1,023
star
4

maglev

🚝 A Tmux theme made to work together with bullet-train.zsh
Shell
456
star
5

blooming-menu.js

🌸 AwesomeMenu made with CSS
JavaScript
289
star
6

webpack-conditional-loader

C conditionals directive for JavaScript
JavaScript
110
star
7

tubo.js

🏄 Your functional (sync/async) pipe | operator
JavaScript
72
star
8

superstylin

Enta in de dance, plug it in and we begin.
HTML
71
star
9

js-console-sublime-snippets

💻 JavaScript and CoffeeScript Console snippets
CoffeeScript
61
star
10

video-stream.js

🔜 📼 Video stream middleware for express.js
JavaScript
43
star
11

js-konami-code-event

Konami code event for your HTML5 web app/page
JavaScript
40
star
12

alfred-chrome-window-workflow

Alfred.app workflow for creating new Chrome windows
AppleScript
37
star
13

jasmine-sublime-snippets

Snippets for Jasmine, the BDD framework for testing JavaScript, in Sublime Text
Python
35
star
14

monocle-decorators.js

🎩 Classy decorators
JavaScript
32
star
15

chrome-blank-new-tab

Dark blank new tab extension for Chrome.
HTML
31
star
16

keynote-grid

A grid template for Keynote.app
30
star
17

piao-da-casa-propria-em-css-3d

Pião da Casa Própria 100% em HTML5
HTML
28
star
18

laughing-man.js

JavaScript
22
star
19

safe-chain.js

🔗 No more crazy checks to safely get a nested value inside an object
JavaScript
21
star
20

redux-whenever.js

🕟 Redux store subscriber for specific state change
JavaScript
21
star
21

parse-price.js

💵 Returns a Number from a localized price string.
JavaScript
21
star
22

alfred-iterm-workflow

Alfred.app workflow for iTerm2
AppleScript
19
star
23

javascript-environments-logos

PostScript
15
star
24

html-style-guide

13
star
25

hide-virtual-keyboard.js

📱 Hides virtual keyboard on a real mobile device (iPhone, Android, ...)
JavaScript
12
star
26

ken-burns-slideshow

🎇 A slideshow in JS with the Ken Burns effect.
JavaScript
12
star
27

knowledge

📖 Tips and tricks I learned along the way
12
star
28

js-debounce-throttle-visual-explanation

A visual explanation about the *Throttle* and *Debounce* design patterns
JavaScript
11
star
29

alfred-credit-card-numbers

Credit card fake numbers workflow for Alfred.app
Python
8
star
30

redux-logdown.js

Redux logging middleware
JavaScript
8
star
31

alfred-feline-theme

An OS X-like theme for Alfred
8
star
32

stubbable-decorator.js

🌲 Decorator to stub modules in ECMAScript 2015+
JavaScript
8
star
33

obstructed.js

🚏 Checks if the main thread is busy, executing a callback whenever it happens
JavaScript
7
star
34

with-subscribe.js

Minimal Observable interface to watch for object modifications.
JavaScript
7
star
35

logdown-cast.js

📡 Subscribe to a remote logdown instance
JavaScript
6
star
36

city-state.js

👑 Observable and encapsulated state management
JavaScript
6
star
37

times-square

Color scheme
JavaScript
6
star
38

caiogondim.com

📝 where i write about random things, at random times
JavaScript
6
star
39

timeout-racer.js

🏎️ Timeout for promises race
JavaScript
5
star
40

simopen

📱 Opens given URL on iOS simulator.
JavaScript
5
star
41

quickreturn.js

:squirrel: QuickReturn Android pattern to the web
JavaScript
5
star
42

jquery-first-event

🏆 Execute your event listener callback before others
JavaScript
5
star
43

hourglass.js

JavaScript
4
star
44

js-underscore.tmbundle

A TextMate bundle for the JavaScript Underscore library
4
star
45

css3-lightbulb-with-ambient-light-sensor

a light bulb in CSS3 with ambient light awareness
CSS
4
star
46

react-with-dimensions

⚛️ React decorator to receive dimensions props generated by ResizeObserver.
JavaScript
4
star
47

solar-system

A solar system entirely built with <canvas> and no external libs
JavaScript
4
star
48

arg-type.js

Like prop-types, but for vanilla JavaScript
JavaScript
4
star
49

programming-challenges

Rust
3
star
50

alfred-sublime-text-window-workflow

A workflow to create Sublime Text windows without having to be in it's context.
AppleScript
3
star
51

resilient.js

Resilient JS loader
JavaScript
3
star
52

docker-node-puppeteer

Dockerfile
3
star
53

gridlock.css

🚙 🚗 Small CSS grid layout implemented with flexbox
HTML
3
star
54

corleone.js

DOM utilities
JavaScript
3
star
55

idle-promise.js

requestIdleCallback with a Promise interface and setTimeout fallback
JavaScript
2
star
56

murmurhash-wasm

2
star
57

js-style-guide

A remix of everybody's JavaScript style guide
JavaScript
2
star
58

sieve-of-eratosthenes-rust

Rust
2
star
59

signalhub-server.js

2
star
60

observable.js

Minimal Observable interface
2
star
61

alfred-firefox-window-workflow

new Firefox window workflow for Alfred.app
AppleScript
2
star
62

webpix

Um experimento HTML5 com câmera, canvas e download sem back-end
JavaScript
2
star
63

css-transform-interactive

Learn CSS transform in a more interactive and fun way
CSS
2
star
64

dotfiles

⚪ My dotfiles
Lua
2
star
65

gulp-filename-hint

Gulp plugin for linting filenames
JavaScript
2
star
66

strict-dict.js

Object (dictionary) that throws TypeError when trying to get an undefined property.
JavaScript
2
star
67

node-calculadora

Exemplo de projeto Git para o Front-end United
JavaScript
1
star
68

msleep

⛔ Small function that mimics the usleep C function, blocking the main thread
JavaScript
1
star
69

white-lion

A Growl Theme based on OS X Lion
1
star
70

css-style-guide

1
star
71

get-highest-z-index.js

JavaScript
1
star
72

tip-calculator

HTML
1
star
73

async-preload-img

Promise based image preloader
JavaScript
1
star
74

react-prefetchable

JavaScript
1
star
75

hal

JavaScript
1
star
76

mouse-polling-rate

HTML
1
star
77

sale.caiogondim.com

I'm moving to New York and selling all my stuff for a reasonable price.
HTML
1
star
78

strip-margin.js

JavaScript
1
star
79

eslint-direct-children-dependency

1
star
80

set-state-redux.js

Love and setState is all you need
JavaScript
1
star
81

invoke-without-new.js

Invoke constructors without new
JavaScript
1
star
82

type-from.js

Get type from given argument
JavaScript
1
star
83

advent-of-code-2022

1
star
84

streams

repository hosting test streams used by hls.js
1
star
85

alfred-itunes-playback-workflow

An Aflred.app workflow to control repeat and shuffle in iTunes
AppleScript
1
star
86

mocker

JavaScript
1
star