petrosh / snippetrosh

Notes with Issues
MIT License
1 stars 3 forks source link

CoffeeScript #17

Open petrosh opened 8 years ago

petrosh commented 8 years ago

CoffeeScript


Conditions styles

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

Defaults

message = evilMessage ? "Exterminate!"
# means
message = if evilMessage? then evilMessage else "Exterminate!"
petrosh commented 6 years ago

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 commented 6 years ago

Operators & Math

Logical

Integer part (floor)

~~(10/3)

Rest (remainder)

(10%3)
trasparente commented 4 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

Ajax

The callback hooks provided by $.ajax() are as follows:

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 commented 2 years ago

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 commented 1 year ago

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 commented 1 year ago

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"