-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
CoffeeScript #17
Comments
DatesDifference 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 |
ObjectsEmpty 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 SetterConvert 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 |
jQueryDOM ready $ ->
console.log "DOM is ready" Click event $(".button").on "click", (event) ->
event.preventDefault() Move element # TOC
tocMove = $ '#markdown-toc'
.prependTo "#panel-toc" Attributesif 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=""` Versions// jQuery
try $().jquery catch e then $().jquery
// Bootstrap
try $.fn.tooltip.Constructor.VERSION catch e then ''
// d3
try d3.version catch e then '' Templatetemplate = $ $("#template").clone().prop "content" |
Promises$.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) |
ArrayDefine 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 |
StringsString 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 |
LoopArraysresult = (item for item in array when item.name is "test") ObjectsSort 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} ] DOM Elements# 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 Loop function# 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() ArraysLoop 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 ObjectsyearsOld = 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' |
PrototypeObject
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"} Functions |
Defaultsmessage = evilMessage ? "Exterminate!"
# means
message = if evilMessage? then evilMessage else "Exterminate!" |
FunctionsImmediately 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"); |
Operators & MathLogical
Integer part (floor) ~~(10/3) Rest (remainder) (10%3) |
ExistenceExistence operator (fail on [null,undefined,0,"",{}].map (e) ->
if e? then console.log e, "si" else console.log e, "no"
Normal test ( [null,undefined,0,"",{}].map (e) ->
if e then console.log e, "si" else console.log e, "no"
|
TypeOfif 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 |
URLSplit 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 |
AjaxThe callback hooks provided by $.ajax() are as follows:
|
FormsReset<!-- 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 |
Cachehttps://developer.mozilla.org/en-US/docs/Web/API/CacheStorage # 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 |
Switch# @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
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
The text was updated successfully, but these errors were encountered: