Skip to content

Commit 1785462

Browse files
committed
array | obj shorthand technique.
1 parent 62c20f8 commit 1785462

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

js-coding-technique/array-find.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Longhand:
2+
3+
const pets = [
4+
{ type: 'Dog', name: 'tommy' },
5+
{ type: 'Cat', name: 'miu' },
6+
{ type: 'Dog', name: 'maxxian' }
7+
];
8+
9+
function findDog(name) {
10+
for (let i = 0; i < pets.length; ++i) {
11+
if (pets[i].type === 'Dog' && pets[i].name === name) {
12+
return pets[i];
13+
}
14+
}
15+
}
16+
17+
// Shorthand:
18+
19+
pet = pets.find(pet => pet.type === 'Dog' && pet.name === 'tommy');
20+
console.log(pet); // { type: 'Dog', name: 'tommy' }

js-coding-technique/obj-key.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// longhand
2+
function validate(values) {
3+
if (!values.first) return false;
4+
if (!values.last) return false;
5+
return true;
6+
}
7+
8+
console.log(validate({ first: 'Bruce', last: 'Wayne' })); // true
9+
10+
// Shorthand:
11+
12+
// object validation rules
13+
const schema = {
14+
first: {
15+
required: true
16+
},
17+
last: {
18+
required: true
19+
}
20+
};
21+
22+
// universal validation function
23+
const validate = (schema, values) => {
24+
for (field in schema) {
25+
if (schema[field].required) {
26+
if (!values[field]) {
27+
return false;
28+
}
29+
}
30+
}
31+
return true;
32+
};
33+
34+
console.log(validate(schema, { first: 'Bruce' })); // false
35+
console.log(validate(schema, { first: 'Bruce', last: 'Wayne' })); // true

0 commit comments

Comments
 (0)