Skip to content
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

Open
petrosh opened this issue Oct 27, 2015 · 18 comments
Open

CoffeeScript #17

petrosh opened this issue Oct 27, 2015 · 18 comments

Comments

@petrosh
Copy link
Owner

petrosh commented Oct 27, 2015

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:
temp or= {} # Yes
temp = temp || {} # No

Conditional Assign

reused = if p.reused then '*' else ''

Set Interval

setInterval ->
  window.location = '{{ site.baseurl }}/'
  # window.location.reload(true) Use this only for Anchor redirects
  return # this prevent return window.location
, 500

Comprehensions

fill = ->
  books = [
    {name: 'Dune', rating: 5}
    {name: "Old Man's War", rating: 4}
    {name: 'Foundation', rating: 3}
  ]
  good = (b.name for b in books when b.rating > 3)
  good

# fill() return ["Dune", "Old Man's War"]

Event Listener

header.addEventListener 'click', (e) => window.location = "/"

Hide Body

document.body.style.display = 'none'

Elements attributes

button.setAttribute 'disabled', 'true'
button.getAttribute 'data-time'
button.removeAttribute 'disabled'

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]

XMLHttpRequest

# XMLHttpRequest.coffee
loadJSON = (url) ->
  req = new XMLHttpRequest()
  req.addEventListener 'readystatechange', ->
    if req.readyState is 4 # ReadyState Complete
     successResultCodes = [200, 304]
     if req.status in successResultCodes
      cb JSON.parse req.responseText
      return
     else
      cb 'error'
      return
  req.open 'GET', url, true
  req.send()
  return

Octokat

octo = new Octokat {}
repo = octo.repos('username', 'repository')

fetch

repo.contents('filename').fetch {ref: "branch"}
.then (fetch) ->
  what = JSON.parse atob fetch.content # Example a json file
  return

Design pattern

@petrosh petrosh added the Time label Jan 6, 2016
@petrosh petrosh mentioned this issue Jan 8, 2016
4 tasks
@petrosh petrosh changed the title Javascript Javascript [URLs](https://github.com/petrosh/snippetrosh/issues/17#issuecomment-184627985) Aug 26, 2016
@petrosh petrosh changed the title Javascript [URLs](https://github.com/petrosh/snippetrosh/issues/17#issuecomment-184627985) Javascript Aug 26, 2016
@petrosh petrosh changed the title Javascript Javascript – URLs Boilerplates XHR BASE64 Time Bookmarks Strings Aug 27, 2016
@petrosh petrosh changed the title Javascript – URLs Boilerplates XHR BASE64 Time Bookmarks Strings CoffeeScript Mar 4, 2017
@petrosh
Copy link
Owner Author

petrosh commented Mar 4, 2017

Dates

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

@petrosh
Copy link
Owner Author

petrosh commented Jun 1, 2017

Objects

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

Setter

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

@petrosh
Copy link
Owner Author

petrosh commented Jun 1, 2017

jQuery

DOM ready

$ ->
  console.log "DOM is ready"

Click event

$(".button").on "click", (event) ->
  event.preventDefault()

Move element

# TOC
tocMove = $ '#markdown-toc'
	.prependTo "#panel-toc"

Attributes

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=""`

Versions

// 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 = $ $("#template").clone().prop "content"

@petrosh
Copy link
Owner Author

petrosh commented Jun 1, 2017

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)

@petrosh
Copy link
Owner Author

petrosh commented Jun 11, 2017

Array

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

@petrosh
Copy link
Owner Author

petrosh commented Nov 12, 2017

Strings

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

@petrosh
Copy link
Owner Author

petrosh commented Nov 30, 2017

Loop

Arrays

result = (item for item in array when item.name is "test")

Objects

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} ]

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()

Arrays

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

Objects

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'

@petrosh
Copy link
Owner Author

petrosh commented Dec 17, 2017

Prototype

Object

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"}

Functions

@petrosh
Copy link
Owner Author

petrosh commented Jan 19, 2018

Defaults

message = evilMessage ? "Exterminate!"
# means
message = if evilMessage? then evilMessage else "Exterminate!"

@petrosh
Copy link
Owner Author

petrosh commented Feb 1, 2018

Functions

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");

@petrosh
Copy link
Owner Author

petrosh commented Mar 17, 2018

Operators & Math

Logical

  • && And
  • || Or
  • ? Not

Integer part (floor)

~~(10/3)

Rest (remainder)

(10%3)

@trasparente
Copy link
Collaborator

Existence

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

@trasparente
Copy link
Collaborator

TypeOf

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

@trasparente
Copy link
Collaborator

URL

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

@trasparente
Copy link
Collaborator

trasparente commented Dec 30, 2021

Ajax

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.
  • Promise callbacks — .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 ' '

check 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

@trasparente
Copy link
Collaborator

Forms

Reset

<!-- 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

@trasparente
Copy link
Collaborator

Cache

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

@trasparente
Copy link
Collaborator

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants