Open petrosh opened 8 years ago
Difference in days
today = new Date()
practice = new Date(p.date)
milliseconds = 1000*60*60*24
console.log Math.round (today-practice) / milliseconds
Format
new Date().toLocaleTimeString("it-IT",{
weekday: "short",
day: "2-digit",
month: "short",
hour: '2-digit',
minute: '2-digit'
})
# mar 05 gen, 16:53
Empty object
yml.html if Object.keys(obj).length then YAML.stringify [obj] else ''
Check existence
# obj exist
if obj?
# object is not undefined or null
# key exist
if obj.key?
# obj.key is not undefined or null
# call function if it exists
obj.funcKey?()
# chain existence checks, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?.grandChildKey
# chain existence checks with function, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?().grandChildKey
Convert JavaScript string in dot notation into an object reference and set a value
# Convert JavaScript string in dot notation into an object reference
# based on https://stackoverflow.com/a/6394168/3469233
setter = (o, path, value) ->
if typeof path is 'string'
return setter o, path.split('.'), value
else if path.length==1 & value!=undefined
return o[path[0]] = value
else if path.length==0
return o
else
if path[1]? & isNaN(path[1]) then o[path[0]] = {} else o[path[0]] = o[path[0]] || []
return setter o[path[0]], path.slice(1), value
DOM ready
$ ->
console.log "DOM is ready"
Click event
$(".button").on "click", (event) ->
event.preventDefault()
Move element
# TOC
tocMove = $ '#markdown-toc'
.prependTo "#panel-toc"
if element.attr('present')?
# is present even with no value
else
# not present
if element.attr('present')
# has a value
else
# not present or no value `present=""`
// jQuery
try $().jquery catch e then $().jquery
// Bootstrap
try $.fn.tooltip.Constructor.VERSION catch e then ''
// d3
try d3.version catch e then ''
template = $ $("#template").clone().prop "content"
$.when(
$.get("/feature/", (html) ->
globalStore.html = html;
),
$.get("https://cdn.css-tricks.com/style.css", (css) ->
globalStore.css = css;
)
).then ->
$("<style />").html(globalStore.css).appendTo("head")
$("body").append(globalStore.html)
Define
students =[
name: "Mohammed"
age: 24
phone: 9848022338
,
name: "Ram"
age: 25
phone: 9800000000
,
name: "Ram"
age: 25
phone: 9800000000
]
Traversing
# The array and object we use for testing
arr = [1, 2, 3, 4, 5]
obj = {a: 1, b: 2, c: 3, d: 4, e: 5}
#
# in
# 5 in arr: true
# 5 in obj: false
# e in obj: false
#
# of
# 5 of arr: false
# 5 of obj: false
# e of obj: true
String contains
# Usage
if /caps/.test u then id = launch.cap_serial
match = /sample/.test "Sample text"
# => false
match = /sample/i.test "Sample text"
# => true
Leading zero
leading_0 = (number) -> "0#{number}".slice -2
result = (item for item in array when item.name is "test")
Sort objects in place by property
# r = [ {launch_date_unix: 3}, {launch_date_unix: 1} ]
r.sort (obj1, obj2) => obj1.launch_date_unix - obj2.launch_date_unix
# r = [ {launch_date_unix: 1}, {launch_date_unix: 3} ]
# Active navbar link on dropdowns
$('li.dropdown').each ->
if $(@).find('div.dropdown-menu a.active').length then $(@).addClass 'active'
true
// Classic
$('li.dropdown').each (i,e) ->
if $(e).find('div.dropdown-menu a.active').length then $(e).addClass 'active'
true
# Better each() for use with coffeescript
# 1. Wraps child in jquery object
# 2. Sets child first argument, so that fat-binding can be used.
# 3. Sets @ as well, for normal binds
jQuery.fn.loop = (block) ->
for i in @
element = jQuery(i)
res = block.call element, element
break if res == false
# Usage
$('.photo').loop ->
@hide()
Loop a nested array
http://petrosh.github.io/ops/#op=percent&1,5/0,3
terms.map (first_term, i) ->
first_term.map (second_term, j) ->
terms[i][j] = second_term.replace ',', '.'
# the same
for first_term, i in terms
for second_term, j in first_term
terms[i][j] = second_term.replace ',', '.'
Associative array:
ages = {}
ages["jim"] = 12
ages["john"] = 7
for key, value of ages
console.log key + " is " + value
Indexed array:
arr = ["a","b","c"]
for value in arr
console.log "value without the key is :" + value
for value, key in arr
console.log key + " is " + value
yearsOld = john: 10, bob: 9, lisa: 11
for child, age of yearsOld
console.log child + ' has ' + age + ' year old'
To avoid properties inherited by the prototype:
for own child, age of yearsOld
console.log child + ' has ' + age + ' year old'
Object::func
replace Object.prototype.func
Object::foo = (zio) ->
this.foo = zio
console.log this
return
load = {
cities: [
{ name: "Rome", role: "capital" }
{ name: "Milan", role: "drink" }
]
}
load.foo 'foo-value'
# {cities: Array(2), foo: "foo-value"}
message = evilMessage ? "Exterminate!"
# means
message = if evilMessage? then evilMessage else "Exterminate!"
Immediately invoked
# Immediately Invoked Function Expressions
login.init = (-> if login.storage()['token'] then login.setLogout() else login.setLogin())()
Self invoking
do f = -> console.log 'ok'
# f = (function(){
# // something
# })();
Self invoking with argument
do (a = 'hello') ->
console.log a
# (function(a) {
# return console.log(a);
# })("hello");
Logical
&&
And||
Or?
NotInteger part (floor)
~~(10/3)
Rest (remainder)
(10%3)
Existence operator (fail on null
and undefined
)
[null,undefined,0,"",{}].map (e) ->
if e? then console.log e, "si" else console.log e, "no"
null no
undefined no
0 si
<empty string> si
Object { } si
Normal test (true
only for objects)
[null,undefined,0,"",{}].map (e) ->
if e then console.log e, "si" else console.log e, "no"
null no
undefined no
0 no
<empty string> no
Object { } si
if typeof value is 'string' then #string
if Array.isArray value then #array
if typeof value is 'object' then #object
if typeof value is 'boolean' then #boolean
Split url
# for username.github.io/repository/#3
path.point = window.location.host.split( '.' )
path.slash = window.location.pathname.split( '/' )
path.hash = parseInt window.location.hash.substring(1) # striped symbol
username = path.point[0]
repository = path.slash[1]
Reload with the new SHA as hash
location.assign "#{location.origin}#{location.pathname}##{data[0].sha}"
location.reload true
The callback hooks provided by $.ajax() are as follows:
beforeSend
callback option is invoked; it receives the jqXHR object and the settings object as parameters.error
callback option is invoked, if the request fails. It receives the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".dataFilter
callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success.success
callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object..done(), .fail(), .always(), and .then()
— are invoked, in the order they are registered.complete
callback option fires, when the request finishes, whether in failure or success. It receives the jqXHR object, as well as a string containing the success or error code.ajaxSend
and ajaxComplete
# Log request send on console
$(document).ajaxSend (options, request, ajaxOptions) ->
console.count ['▲', ajaxOptions.type, ajaxOptions.url].join ' '
# Log request send on console
$(document).ajaxComplete (options, request, ajaxOptions) ->
console.count ['▼', ajaxOptions.type, ajaxOptions.url].join ' '
remote_theme
release tag# Check remote theme
if '{{ site.remote_theme }}' isnt ''
[remote, branch] = '{{ site.remote_theme }}'.split '@'
ajax_data = if branch then {sha: branch} else {}
# Get latest release
latest_url = "{{ site.github.api_url }}/repos/#{remote}/releases/latest"
latest_tag = $.get latest_url,
data: ajax_data
latest_tag.done (data) ->
data = cache data, latest_url
published_at = +new Date(data.published_at)
# Compare latest release published_at with storage.repository.remote_release
if published_at > storage.get 'repository.remote_release'
# Update remote_release in storage
storage.set 'repository.remote_release', published_at
notification "Remote theme changed #{data.tag_name} #{time_diff data.published_at}"
return # End remote TAG check
<!-- FILTER template -->
<template id='template-filter'>
<div class='filter'>
<label for='column'>Filter</label>
<select class='inline' name='column'></select>
<input type='text' name='value' placeholder='Value'>
<a href='#reset' class='prevent-default'>Reset</a>
</div>
</template>
# Reset filter event
$(document).on 'click', '.filter a[href="#reset"]', (e) ->
e.preventDefault()
filter = $(e.target).parents '.filter'
filter.find('select[name=column]').prop 'selectedIndex', null
filter.find('input').val ''
filter.find('select[name=column]').trigger 'input'
return # End reset event
https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
Doesn't work over HTTP
, return error on http://0.0.0.0:4000
.
# polyfill
cache = if caches? then caches.open 'github-rest-api' else Promise.resolve()
cache.catch (err) -> console.log err
cache.then (value) -> console.log value
# @function {fill}: Fill div with products list
fill = ->
console.log 'ok'
# Check page reading first body class
switch document.body.classList[0]
when "products-md" then fill()
name="Ramu"
score=75
message = switch
when score>=75 then "Congrats your grade is A"
when score>=60 then "Your grade is B"
when score>=50 then "Your grade is C"
when score>=35 then "Your grade is D"
else "Your grade is F and you are failed in the exam"
console.log message
message = switch name
when "Ramu","Mohammed" then "You have passed the examination with grade A"
when "John","Julia" then "You have passed the examination with grade is B"
when "Rajan" then "Sorry you failed in the examination"
else "No result"
CoffeeScript
Caches
Official helpers
Conditions styles
and
is preferred over&&
.or
is preferred over||
.is
is preferred over==
.isnt
is preferred over!=
.not
is preferred over!
.or=
should be used when possible:Conditional Assign
Set Interval
Comprehensions
Event Listener
Hide Body
Elements attributes
Split url
XMLHttpRequest
Octokat
fetch
Design pattern