2021년 1월 18일 월요일

Using the SetCacheHeaders middleware

 

  • no-cache and etag will allow the user to refresh the page (even before the expiration time) without downloading the whole page if the latest published podcasts are still the same.
  • private says the homepage is per-user, and should be cached only in the user device rather than, for example, a proxy.
  • max-age=300 will set an expiration time of 5 minutes, since after that time surely there is a new Podcast published.

Route::get('/', 'PodcastController@index')
->middleware('cache.headers:no-cache,private,max-age=300;etag');

2021년 1월 2일 토요일

Useful HTML5 Features

 

1. Datalist


<body>
<form action="" method="get">
<label for="fruit">Choose your fruit :</label>
<input list="fruits" name="fruit" id="fruit">
<datalist id="fruits">
<option value="Apple">
<option value="Orange">
<option value="Banana">
<option value="Mango">
<option value="Avacado">
</datalist>
<input type="submit">
</form>
</body>

2. The details tag

<body>
<details>
<summary>Click to get the user details</summary>
<table>
<tr>
<th>Name</th>
<th>Date of birth</th>
<th>Job</th>
</tr>
<tr>
<td>John</td>
<td>March 19</td>
<td>Accountant</td>
</tr>
</table>
</details>
</body>

3. The output tag

<form oninput="x.value=parseInt(a.value) * parseInt(b.value)">
<input type="number" id="a" value="0">
* <input type="number" id="b" value="0">
= <output name="x" for="a b"></output>
</form>

4. Content editable

By setting this attribute to true you will be able to edit the content of an element.

<div> <h1> Employees list </h1> <ul class="content-editable" contenteditable="true"> <li> 1. Jhon </li> <li> 2. Mehdi </li> <li> 3. Brad </li> </ul> </div>

5. The meter tag

<label for="low">Low</label>
<meter id="low" min="0" max="100" low="30" high="75" optimum="80" value="25"></meter>
<label for="medium">Medium</label>
<meter id="medium" min="0" max="100" low="30" high="75" optimum="80" value="50"></meter>
<label for="high">High</label>
<meter id="high" min="0" max="100" low="30" high="75" optimum="80" value="80"></meter>

6. The download attribute

<div>
<a href="index.html" download="fileName">Download HTML</a>
</div>

7. Defer and Async attributes


<script src="app.js" defer></script>
<script src="app.js" async></script>

You don’t need to put the script tags at the bottom of the body tag anymore.

8. The abbr tag


<h2><abbr title="JavaScript and XML">JSX</abbr> is awesome.</h2>

9. Accept

<input type="file" accept=".jpg, .png" >

파일 찾기 시 해당 확장자만 탐색이에서 열린다.

10. Content editable

<div>
<h1> Employees: </h1>
<ul contenteditable="true">
<li> 1. John </li>
<li> 2. Mehdi </li>
<li> 3. James </li>
</ul>
</div>

11. Download

<div>
<a href="index.html" download="fileName">Download this</a>
</div>

12. Poster

The attribute poster is used to display an image while an HTML video is downloading, or until the user clicks on the play button.

<video poster="picture.jpeg" controls> <source src="file.mp4" type="file/mp4"> <source src="file.ogg" type="file/ogg"> </video>

13. Native HTML accordion

<div class="container"> <details> <summary> HTML stands for? </summary> <p>HTML stands for hyper text markup language.</p> </details> </div>

14. Lazy loading images using HTML

<img src='imageSrc.jpg' loading='lazy' alt='image description'>

15. Copying text to clipboard

function CopyText() { // select the text element. let text = document.getElementById("myText"); // select text. text.select(); text.setSelectionRange(0, 99999); // Copying the text inside the text field navigator.clipboard.writeText(text.value); //if you want an a copy alert. alert("Copied the text: " + text.value); }

16. Scroll to the top

const ScrollTop = () => window.scrollTo(0, 0);
ScrollTop();

17. Easily create a color picker

<input type="color" value="#000">

18. Easily create a color picker

The hidden attribute is a boolean attribute.
When present, the browsers won’t display elements that have the hidden attribute specified.

<p hidden>You won't see me on the browser, only developers can!</p>

19. Accept

<form action="/..."> <label for="img">Select image:</label> <input type="file" id="img" name="img" accept="image/*"> <input type="submit"> </form> <!-- or --> <input type="file" accept=".jpg, .png" >

20. Controlling Context Menu and Paste

<input type="text" onpaste="return false" value="Paste something in here"> <div oncontextmenu="myFunction()" contextmenu="mymenu">

You can listen to events like when they use right-clicks or try to paste content and handle these events with oncontextmenu and onpaste attributes. If you don’t want users to be able to paste onto some field like password, you can write onpaste=”return false” on that input field and users won’t be able to paste there. Similarly, oncontextmenu fires whenever the user right-clicks on that element.

21. Range

<head>
<script>
function changeValue(event) {
let value = event.target.value;
let output = document.getElementById('output');
output.value = value;
}
</script>
</head>
<body>
<form method="post">
<input
type="range"
name="range"
min="0"
max="100"
step="1"
value=""
onchange="changeValue(event)"/>
</form>
<div class="range">
<output id="output" name="result"> </output>
</div>
</body>


22. Progress

<label for="home">6/10 tasks done</label>
<progress value="60" max="100" id="home"></progress>


23. Color picker

<p id="colorPicker">Color Picker!</p>
<input type="color" onchange="showColor(event)">


24. Mark content

<p>Did you know that <mark>not all heroes wear capes.</mark></p>

25. Abbreviation

<p>Agent Phil Coulson leads a team of highly skilled agents from the global law-enforcement organisation known as
<abbr title="Strategic Homeland Intervention, Enforcement, and Logistics Division">SHIELD</abbr>.
</p>


26. <del> and <ins>

<p><del>Iron Man</del> <ins>Captain America</ins> is ehmmm.. yea the captain!</p>

27. Output

<form oninput="x.value=parseInt(a.value) * parseInt(b.value)">
<input type="number" id="a" value="0"> * <input type="number" id="b" value="0">
= <output name="x" for="a b"></output>
</form>

28. Time

The <time> tag defines a specific time (or datetime).

The datetime attribute of this element is used to translate the time into a machine-readable format so that browsers can offer to add date reminders through the user's calendar, and search engines can produce smarter search results.

<p>The next assemble meeting is postponed on <time datetime="2022-12-01">2022-12-01</time>.</p>

29. Audio

The <audio> tag will define a sound and there are three supported files which the tag can be used with. These are MP3, WAV, and OGG. A browser will then select the first one it supports.

<audio controls>
<source src=”introduction.ogg” type=”audio/ogg”>
<source src=”introduction.mp3” type=”audio/mpeg”>
Your browser does not support this audio
</audio>











55 Tips For JavaScript

 

1. Use ‘const’ for the constants instead of ‘var’

/* Old way */
var i = 1;
/* Correct */
const i = 1;

2. Use ‘let’ for the changing variables instead of ‘var’

/* Inadequate */
var myVal = 1;
for (var i; i < 10; i++){
myVal = 1 + i;
}
/* Correct */
let myVal = 1;
for (let i; i < 10; i++){
myVal += i
}

3. Declaring Objects

/* 
Old way
The Object() class makes an unnecessary function call
*/
const myObject = new Object();
/* Correct */
const myObject = {};

4. Declaring Arrays

/* 
Old way
The Array() class makes an unnecessary function call
*/
const myArray = new Array();
/* Correct */
const myArray = [];

5. Concatenate strings

/* Old way */
const myStringToAdd = "world";
const myString = "hello " + myStringToAdd;
/* Correct */
const myStringToAdd = "world";
const myString = `hello ${myStringToAdd}`;

6. Use object method shorthand

/* Inadequate */
const customObject = {
val: 1,
addVal: function () {
return customObject.val + 1;
}
}
/* Correct */
const customObject = {
val: 1,
addVal(){
return customObject.val++
}
}

7. Creating the value of an Object

/* Inadequate */
const value = 1;
const myObject = {
value: value
}
/* Correct */
const value = 1;
const myObject = {
value
}

8. Assign values to an Object

/* Old way */
const object1 = { val: 1, b: 2 };
let object2 = { d: 3, z: 4 };
object2.val = object1.val;
object2.b = object1.b;
/* Correct */
const object1 = { val: 1, b: 2 };
const object2 = { ...object1, d: 3, z: 4 }

9. Assign a value to an Array

/* Inadequate */
const myArray = [];
myArray[myArray.length] = "hello world";
/* Correct */
const myArray = [];
myArray.push('Hello world');

10. Concatenate Arrays

/* Inadequate */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = array1.concat(array2);
/* Correct */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = [...array1, ...array2]

11. Get multiple properties of an object

/* Inadequate */
function getFullName(client){
return `${client.name} ${client.last_name}`;
}
/* Correct */
function getFullName({name, last_name}){
return `${name} ${last_name}`;
}

12. Getting values from an object

/* Inadequate */
const object1 = { a: 1 , b: 2 };
const a = object1.a;
const b = object1.b;
/* Correct */
const object1 = { a: 1 , b: 2 };
const { a, b } = object1;

13. Creating functions

/* Old way but good */
function myFunc() {}
/* Good */
const myFunc = function() {}
/* Best */
const myFunct = () => {}
// IMPORTANT: In some cases it is not recommended to use these functions with arrows to avoid reading errors

14. Default values

/* Inadequate */
const myFunct = (a, b) => {
if (!a) a = 1;
if (!b) b = 1;
return { a, b };
}
/* Correct */
const myFunct = (a = 1, b = 1) => {
return { a, b };
}

15. Use ‘reduce’ Instead ‘forEach’ and ‘for’ to sum values

/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
values.forEach( (n) => { total += n})
/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
for (let i; i < values.length; i++){
total += values[i];
}
/* Correct */
const values = [1, 2, 3, 4, 5];
const total = values.reduce((total, num) => total + num);

16. Exist in array

/* Inadequate */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
let exist = false;
myArray.forEach( item => {
if (item.a === 2) exist = true
})
/* Correct */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
const exist = myArray.some( item => item.a == 2)

17. Shortcut if boolean

/* Inadequate */
const a = 1;
const b = 1;
let isTrue = false
if (a === b) {
isTrue = true
}
/* Correct */
const a = 1;
const b = 1;
const isTrue = a === b

18. Shortcut if values

/* Inadequate */
const a = 5;
let b;
if (a === 5){
b = 3;
} else {
b = 2;
}
/* Correct */
const a = 5;
const b = a === 5 ? 3 : 2;

19. Resize or Empty an Array Using array.length


array.length = nvar array = [a, b, c, d, e, f, g, h, i , j];
console.log(array.length); // returns the length as 10
array.length = 4;
console.log(array.length); // returns the length as 4
console.log(array); // returns “a,b,c,d”

var array = [a, b, c, d, e, f, g, h, i , j];
array.length = 0;
console.log(array.length); // returns the length as 0console.log(array);


20. How to Merge Arrays Without Causing Server Overload
var list1 = [a, b, c, d, e];
var list2 = [f, g, h, i, j];
console.log(list1.push.apply(list1, list2));
// returns the merged values of both arrays (a, b, c, d, e,f, g, h, i, j)

21. How to Extract Unique Values
const cars = ['Opel','Bugatti','Opel','Ferrari','Ferrari','Opel'];
var unrepeated_cars = [...new Set(cars)]; // spread Operator
console.log(unrepeated_cars); // returns the values Opel, Bugatti, Ferrari


22. How to Check if an Object Has Values
Object.keys(objectName).length// if it returns 0 then the Object is empty,// otherwise it displays the number of values

23. Assigning values to multiple variables

//Longhand 
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];


24. Assigning default value
//Longhand 
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}

//Shorthand
let imagePath = getImagePath() || 'default.jpg';

25. AND(&&) Short circuit evaluation

//Longhand 
if (isLoggedin) {
goToHomepage();
}

//Shorthand
isLoggedin && goToHomepage();
<div> { this.state.isLoading && <Loading /> } </div>

26. Swap two variables
let x = 'Hello', y = 55; //Longhand 
const temp = x;
x = y;
y = temp;

//Shorthand
[x, y] = [y, x];

27. Multi-line String
//Longhand 
console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' +
'ECMAScript specification. JavaScript is high-level,\n' +
'often just-in-time compiled, and multi-paradigm.' );
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);

28. Multiple condition checking
//Longhand 
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}

// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}

29. Object Property Assignment
let firstname = 'Amitav'; 
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};

//Shorthand
let obj = {firstname, lastname};

30. String into a Number
//Longhand 
let total = parseInt('453');
let average = parseFloat('42.6');

//Shorthand
let total = +'453';
let average = +'42.6';

31. Repeat a string for multiple times
//Longhand 
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello

// Shorthand
'Hello '.repeat(5);
'sorry\n'.repeat(100);

32. Find max and min number in array
// Shorthand 
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

33. For loop
let arr = [10, 20, 30, 40]; //Longhand 
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(`index: ${index} and value: ${arr[index]}`);
}
let obj = {x: 20, y: 50}; 
for (const key in obj) {
console.log(obj[key]);
}


34. Merging of arrays
let arr1 = [20, 30]; //Longhand 
let arr2 = arr1.concat([60, 80]);
// [20, 30, 60, 80]

//Shorthand
let arr2 = [...arr1, 60, 80];
// [20, 30, 60, 80]

35. Deep cloning of multi-level object
let obj = {x: 20, y: {z: 30}}; 
//Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};


36. Get character from string
let str = 'jscurious.com'; //Longhand 
str.charAt(2); // c

//Shorthand
str[2]; // c

37. Smart Data Filteration

// Data Filterationvar data = ["Football", "Soccer", "Cricket", "Basketball", "Hockey"]var filtered_data = data.filter(data => data.length < 8)console.log(filtered_data) // ["Soccer", "Cricket", "Hockey"]

38. Looping Keys and Values

// looping throught objectslet data = {JavaScript: 1, Dart: 2, Java: 3};Object.keys(data).forEach((key, value) => {  console.log(key, value); });// Output
// JavaScript 0
// Dart 1
// Java 2

39. Destructing assignment

// Destructive Assignmentlet data = ["Haider", "22", "50000", "Web Developer"]let [name, age, salary, profession] = dataconsole.log(name, age, salary, profession) // Haider 22 50000 Web Developer

40. Slicing Array

// Slicing An Arraylet array = [10, 12, 13, 14, 15, 16]console.log(array.slice(0, 3)) // [10, 12, 13]
console.log(array.slice(0, 2)) // [10, 12]

41. Search Object in Array

// Search Object in Arraylet data = [
{name:"haider", Salary:60000},
{name:"John", Salary:50000},
{name:"Peter", Salary:20000},
]
let emp = data.find(data => data.name === "Peter")console.log(emp)
// Output
{
name:"Peter",
Salary:20000
}

42. String Reversing

// String Reversevar reverse = (data) => {return data.split("").reverse().join(""); }console.log(reverse("CoderBoy")) // yoBredoCconsole.log(reverse("Medium")) // muideM

43. Concatenate Lists

let arr1 = [10, 20, 30]
let arr2 = [40, 50]
var arr = arr1.concat(arr2)
console.log(arr) // [10, 20, 30, 40, 50]

44. Capture Right Click

// Capture Right Clickwindow.oncontextmenu = () => {console.log("Right Click is Pressed!")}

45. Built-in Sorting

// Built in Sortingvar num = [9, 8, 4, 2, 8, 0, 3, 8]num.sort()console.log(num) //[0, 2, 3, 4, 8, 8, 9]

46. Handle Errors in JS

// Error Handlingtry {
// Code Block to try
}
catch(err) {
// Code Block to handle errors
}
finally {
// Code Block to be executed regardless of the try and catch results
}

47. Find Index of Array Element

// Index of Elementvar num = [9, 8, 4, 2, 8, 0, 3, 8]console.log(num.indexOf(9)) // 0console.log(num.indexOf(3)) // 6console.log(num.indexOf(8)) // 1

48. Check String is Uppercase

// Check for UpperCase
const CheckUpper = string => string === string.toUpperCase();
console.log(CheckUpper("Hello")) // false
console.log(CheckUpper("LEARN")) // true

49. Reverse a string

const reverseString = (...strArr) => strArr.reverse().join('');

50. Get query parameters from the URL

const getQueryParams = (URL) => JSON.parse(    '{"' +
      decodeURI(URL.split('?')[1])
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
getQueryParams('https://codingcafe.co.in?name=gyan&age=24');
// output
{name: 'gyan', age: '24'}
const getSearchParams = (url) => new URL(url).searchParams;

51. Clipboard API

const copy =    (text) => navigator.clipboard.writeText('Hello world!');

52. Remove duplicate from an Array

const removeDuplicates = (ary) => [...new Set(ary)];
removeDuplicates([5,6,1,2,3,6,3,5,1]) // [5, 6, 1, 2, 3]

53. Check to see if the current tab is visible or focused

const inView = () => document.hidden;
inView();
// Result: returns true or false depending on if tab is focused

54. Check to see if the Element is focused

const inView = (el) => (el === document.activeElement);
inView(element);
// Result: returns true or false depending on if element is focused

55. URL query parameters

const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=test&sex=man"
params.has("test"); // true
params.get("sex"); // "man"

56. Scroll to top or to the bottom

const scrollToTop = () => window.scrollTo(0,0);
scrollToTop();
const scrollToBottom = () => window.scrollTo(0,document.body.scrollHeight); scrollToBottom()

57. Check that Caps Lock is on

const passwordInput = document.getElementById('password');

passwordInput.addEventListener('keyup', function (event) {
    if (event.getModifierState('CapsLock')) {
        // CapsLock is open
    }
}); 

58. Get the mouse position

document.addEventListener('mousemove', (e) => {
    console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
});

59. element’s dataset

<div id="user" data-name="Maxwell" data-age="32" data-something="Some Data">
    Hello Maxwell
</div>

<script>
    const user = document.getElementById('user');
  
    console.log(user.dataset); 
    // { name: "Maxwell", age: "32", something: "Some Data" }
  
    console.log(user.dataset.name); // "Maxwell"
    console.log(user.dataset.age); // "32"
    console.log(user.dataset.something); // "Some Data"
</script>