Javanoscript - Day 17
Throttle
Throttling is a technique used to control how many times we allow a function to be executed over time. When a JavaScript function is said to be throttled with a wait time of X milliseconds, it can only be invoked at most once every X milliseconds. The callback is invoked immediately and cannot be invoked again for the rest of the wait duration.
Implement a throttle function which accepts a callback function and a wait duration. Calling throttle() returns a function which throttled invocations of the callback function following the behavior described above.
Examples
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Throttle
Throttling is a technique used to control how many times we allow a function to be executed over time. When a JavaScript function is said to be throttled with a wait time of X milliseconds, it can only be invoked at most once every X milliseconds. The callback is invoked immediately and cannot be invoked again for the rest of the wait duration.
Implement a throttle function which accepts a callback function and a wait duration. Calling throttle() returns a function which throttled invocations of the callback function following the behavior described above.
Examples
let i = 0;
function increment() {
i++;
}
const throttledIncrement = throttle(increment, 100);
// t = 0: Call throttledIncrement(). i is now 1.
throttledIncrement(); // i = 1
// t = 50: Call throttledIncrement() again.
// i is still 1 because 100ms have not passed.
throttledIncrement(); // i = 1
// t = 101: Call throttledIncrement() again. i is now 2.
// i can be incremented because it has been more than 100ms
// since the last throttledIncrement() call at t = 0.
throttledIncrement(); // i = 2
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
وب سایت سوممون هم اومد بالا :
https://www.chipinbro.com/
با دوستات خوش بگذرون ولی دنگت رو بده.
ابزار محاسبه دنگ و سهم.
بدون نیاز به لاگین. بدون بک اند. بدون اطلاعات شخصی.
https://www.chipinbro.com/
با دوستات خوش بگذرون ولی دنگت رو بده.
ابزار محاسبه دنگ و سهم.
بدون نیاز به لاگین. بدون بک اند. بدون اطلاعات شخصی.
رقصنده با کد
وب سایت سوممون هم اومد بالا : https://www.chipinbro.com/ با دوستات خوش بگذرون ولی دنگت رو بده. ابزار محاسبه دنگ و سهم. بدون نیاز به لاگین. بدون بک اند. بدون اطلاعات شخصی.
تا الان سه تا کار ساده آوردیم بالا با ۴ شعار اصلی :
۱- اگر از نسخه اول پروژهات شرمنده نیستی ، دیر شروع کردی.
۲- اول بزا ، بعد بزرگش کن.
۳- ابزارها نباید نیاز به بکاند مستقل داشته باشن.
۴- تا حد ممکن همه چی رو ساده نگه دار.
سه تا پروژه اینها هستش و توی هر کدوم که بخواید به شکل اپن سورس میتونید مشارکت کنید. تیم دیزاینمون در حال ایجاد دیزاینهای جدید و شکیله. نسخههای فعلی فقط نسخه 0.001 هستش.
payafterdone.com
menuliza.com
chipinbro.com
۲ ابزار دیگه هم در دست بررسیه.
یک در حوزه سلامت ، یکی هم در حوزه تماس تصویری و چت
همه اینها زیر مجموعه چیزیه به نام NoAiStudio
۱- اگر از نسخه اول پروژهات شرمنده نیستی ، دیر شروع کردی.
۲- اول بزا ، بعد بزرگش کن.
۳- ابزارها نباید نیاز به بکاند مستقل داشته باشن.
۴- تا حد ممکن همه چی رو ساده نگه دار.
سه تا پروژه اینها هستش و توی هر کدوم که بخواید به شکل اپن سورس میتونید مشارکت کنید. تیم دیزاینمون در حال ایجاد دیزاینهای جدید و شکیله. نسخههای فعلی فقط نسخه 0.001 هستش.
payafterdone.com
menuliza.com
chipinbro.com
۲ ابزار دیگه هم در دست بررسیه.
یک در حوزه سلامت ، یکی هم در حوزه تماس تصویری و چت
همه اینها زیر مجموعه چیزیه به نام NoAiStudio
یکی از شرکت کنندههای عشق ابدی ، با ۳ هفته حضور در برنامه که میشه یه چیزی حدود ۵ روز یا نهایتا ۱۰ روز حضور در ویلا ، ۳۲ هزار نفر فالوور فقط روی تلگرام گرفته. اینستا و یوتیوب به کنار.
من ۵ ساله فعالیت تخصصی میکنم ، هنوز ۸۰۰ تا نشدیم (به غیر از اون ۲۵۰۰ عزیز از دست رفته)
گاهی اوقات شلوار درآوردن و بیرون ریختن متاسفانه جواب میده.
البته فکر نمیکنم این حرکت از سمت من برای شما خیلی جذاب باشه 😂
حیف لحظاتی که صرف این بیهودهگیها میشه ولی گاهی اوقات برای ساکت کردن صدای ذهن لازمه.
من ۵ ساله فعالیت تخصصی میکنم ، هنوز ۸۰۰ تا نشدیم (به غیر از اون ۲۵۰۰ عزیز از دست رفته)
گاهی اوقات شلوار درآوردن و بیرون ریختن متاسفانه جواب میده.
البته فکر نمیکنم این حرکت از سمت من برای شما خیلی جذاب باشه 😂
حیف لحظاتی که صرف این بیهودهگیها میشه ولی گاهی اوقات برای ساکت کردن صدای ذهن لازمه.
Javanoscript + React - Day 18
useArray
Implement a useArray hook that manages an array of items with additional utility methods.
It is more convenient to use useArray over plain useState because in the latter case, you would always have to create a new array, mutate it, then set state to use the new array, which can be quite cumbersome.
The hook should work generically with arrays of any types.
Arguments
- defaultValue: The initial array of items
Returns
The hook returns an object with the following properties:
- array: The current array of items
- set: (newArray) => void: A function that sets the array of items. This must be the same type as the setter function of useState
- push: (item) => void: A function that adds an item to the end of the array
- remove: (index: number) => void: A function that removes an item from the array by index
- filter: (predicate) => void: A function that filters the array based on a predicate function. predicate must be the same type as the argument of Array.prototype.filter
- update: (index: number, newItem) => void: A function that replaces an item in the array at index
- clear: () => void: A function that clears the array
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
useArray
Implement a useArray hook that manages an array of items with additional utility methods.
It is more convenient to use useArray over plain useState because in the latter case, you would always have to create a new array, mutate it, then set state to use the new array, which can be quite cumbersome.
The hook should work generically with arrays of any types.
const defaultValue = ['apple', 'banana'];
export default function Component() {
const { array, push, update, remove, filter, set, clear } = useArray();
return (
<div>
<p>Fruits: {array.join(', ')}</p>
<button onClick={() => push('orange')}>Add orange</button>
<button onClick={() => update(1, 'grape')}>
Change second item to grape
</button>
<button onClick={() => remove(0)}>Remove first</button>
<button onClick={() => filter((fruit) => fruit.includes('a'))}>
Keep fruits containing 'a'
</button>
<button onClick={() => set(defaultValue)}>Reset</button>
<button onClick={clear}>Clear list</button>
</div>
);
}
Arguments
- defaultValue: The initial array of items
Returns
The hook returns an object with the following properties:
- array: The current array of items
- set: (newArray) => void: A function that sets the array of items. This must be the same type as the setter function of useState
- push: (item) => void: A function that adds an item to the end of the array
- remove: (index: number) => void: A function that removes an item from the array by index
- filter: (predicate) => void: A function that filters the array based on a predicate function. predicate must be the same type as the argument of Array.prototype.filter
- update: (index: number, newItem) => void: A function that replaces an item in the array at index
- clear: () => void: A function that clears the array
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
به مدت ۲.۵ ماه توی کانال فعال نخواهم بود. (تا اواسط اسفند)
پیامهای سوالات ۸۷ روزه جاوااسکریپت ، تنظیم شده که اتوماتیک طبق برنامه پست بشه توی کانال.
ایشالله بعدش با خبر خوب برای خودم و اگر قسمت بشه با خبر خوب برای بقیه میام.
ترکم نکنید 😘
پیامهای سوالات ۸۷ روزه جاوااسکریپت ، تنظیم شده که اتوماتیک طبق برنامه پست بشه توی کانال.
ایشالله بعدش با خبر خوب برای خودم و اگر قسمت بشه با خبر خوب برای بقیه میام.
ترکم نکنید 😘
رقصنده با کد pinned «به مدت ۲.۵ ماه توی کانال فعال نخواهم بود. (تا اواسط اسفند) پیامهای سوالات ۸۷ روزه جاوااسکریپت ، تنظیم شده که اتوماتیک طبق برنامه پست بشه توی کانال. ایشالله بعدش با خبر خوب برای خودم و اگر قسمت بشه با خبر خوب برای بقیه میام. ترکم نکنید 😘»
Javanoscript + React - Day 19
useDebounce
Implement a useDebounce hook that delays state updates until a specified delay has passed without any further changes to the provided value.
The observable outcome of using useDebounce is quite similar to React's useDeferredValue, the former returns an updated value after a fixed duration while the latter always returns the updated value but updates to the DOM relies on React's priority system.
Arguments
1. value: The value to debounce
2. delay: number: The delay in milliseconds
Returns
The hook returns the debounced value.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
useDebounce
Implement a useDebounce hook that delays state updates until a specified delay has passed without any further changes to the provided value.
export default function Component() {
const [keyword, setKeyword] = useState('');
const debouncedKeyword = useDebounce(keyword, 1000);
return (
<div>
<input value={keyword} onChange={(e) => setKeyword(e.target.value)} />
<p>Debounced keyword: {debouncedKeyword}</p>
</div>
);
}
The observable outcome of using useDebounce is quite similar to React's useDeferredValue, the former returns an updated value after a fixed duration while the latter always returns the updated value but updates to the DOM relies on React's priority system.
Arguments
1. value: The value to debounce
2. delay: number: The delay in milliseconds
Returns
The hook returns the debounced value.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript + React - Day 20
useSet
Implement a useSet hook that manages a JavaScript Set of items with additional utility methods.
It is more convenient to use useSet over plain useState because in the latter case, you would always have to create a new Set, mutate it, then set state to use the new set, which can be quite cumbersome.
The hook should work generically with items of any types.
Arguments
- initialState: The initial Set of items
Returns
The hook returns an object with the following properties:
- set: The current set of items
- add: (item) => void: A function that adds item to the set
- remove: (item) => void: A function that removes item from the set
- toggle: (item) => void: A function that toggles the presence of item in the set
- reset: () => void: A function that resets the set to initialState
- clear: () => void: A function that removes all items in the set
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
useSet
Implement a useSet hook that manages a JavaScript Set of items with additional utility methods.
It is more convenient to use useSet over plain useState because in the latter case, you would always have to create a new Set, mutate it, then set state to use the new set, which can be quite cumbersome.
The hook should work generically with items of any types.
export default function Component() {
const { set, add, remove, toggle, reset, clear } = useSet(new Set(['hello']));
return (
<div>
<button onClick={() => add(Date.now().toString())}>Add</button>
<button onClick={() => remove('hello')} disabled={!has('hello')}>
Remove 'hello'
</button>
<button onClick={() => toggle('hello')}>Toggle hello</button>
<button onClick={() => reset()}>Reset</button>
<button onClick={() => clear()}>Clear</button>
<pre>{JSON.stringify(Array.from(set), null, 2)}</pre>
</div>
);
}
Arguments
- initialState: The initial Set of items
Returns
The hook returns an object with the following properties:
- set: The current set of items
- add: (item) => void: A function that adds item to the set
- remove: (item) => void: A function that removes item from the set
- toggle: (item) => void: A function that toggles the presence of item in the set
- reset: () => void: A function that resets the set to initialState
- clear: () => void: A function that removes all items in the set
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript + React - Day 21
useTimeout
Implement a useTimeout hook that invokes a callback function after a specified delay.
Note that the hooks can be called again with different values since the initial call:
- Different callback: The pending timer should invoke the latest callback. If the timer has already expired, the callback is not executed and no new timer will be set
- Different delay: The previous timeout should be cancelled if the timer hasn't expired, a new timer is set with the new delay value
The primary benefit of useTimeout is so that you don't have to manually clear call clearTimeout() if the component unmounts before the timer expires.
Arguments
1. callback: () => void: A function to be called after the specified delay
2. delay: number | null: The delay in milliseconds before the invocation of the callback function. If null, the timeout is cleared
Returns
Nothing.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
useTimeout
Implement a useTimeout hook that invokes a callback function after a specified delay.
Note that the hooks can be called again with different values since the initial call:
- Different callback: The pending timer should invoke the latest callback. If the timer has already expired, the callback is not executed and no new timer will be set
- Different delay: The previous timeout should be cancelled if the timer hasn't expired, a new timer is set with the new delay value
The primary benefit of useTimeout is so that you don't have to manually clear call clearTimeout() if the component unmounts before the timer expires.
export default function Component() {
const [loading, setLoading] = useState(true);
useTimeout(() => setLoading(false), 1000);
return (
<div>
<p>{loading ? 'Loading' : 'Ready'}</p>
</div>
);
}
Arguments
1. callback: () => void: A function to be called after the specified delay
2. delay: number | null: The delay in milliseconds before the invocation of the callback function. If null, the timeout is cleared
Returns
Nothing.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript + React - Day 22
useWindowSize
Implement a useWindowSize hook that returns the current height and width of the window (window.innerHeight and window.innerWidth). It should re-render the component if the screen properties changes.
Arguments
Nothing.
Returns
The hook returns an object with the following properties:
- height: number: Current height of the screen
- width: number: Current width of the screen
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
useWindowSize
Implement a useWindowSize hook that returns the current height and width of the window (window.innerHeight and window.innerWidth). It should re-render the component if the screen properties changes.
export default function Component() {
const screen = useWindowSize();
return (
<div>
<p>The current window dimensions are:</p>
<code>{JSON.stringify(screen, null, 2)}</code>
</div>
);
}
Arguments
Nothing.
Returns
The hook returns an object with the following properties:
- height: number: Current height of the screen
- width: number: Current width of the screen
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript - Day 23
Classnames
classnames is a commonly-used utility in modern front end applications to conditionally join CSS class names together. If you've written React applications, you likely have used a similar library.
Implement the classnames function.
Examples
Arrays will be recursively flattened as per the rules above.
Values can be mixed.
Falsey values are ignored.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Classnames
classnames is a commonly-used utility in modern front end applications to conditionally join CSS class names together. If you've written React applications, you likely have used a similar library.
Implement the classnames function.
Examples
classNames('foo', 'bar'); // 'foo bar'
classNames('foo', { bar: true }); // 'foo bar'
classNames({ 'foo-bar': true }); // 'foo-bar'
classNames({ 'foo-bar': false }); // ''
classNames({ foo: true }, { bar: true }); // 'foo bar'
classNames({ foo: true, bar: true }); // 'foo bar'
classNames({ foo: true, bar: false, qux: true }); // 'foo qux'
Arrays will be recursively flattened as per the rules above.
classNames('a', ['b', { c: true, d: false }]); // 'a b c'
Values can be mixed.
classNames(
'foo',
{
bar: true,
duck: false,
},
'baz',
{ quux: true },
); // 'foo bar baz quux'
Falsey values are ignored.
classNames(null, false, 'bar', undefined, { baz: null }, ''); // 'bar'
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript - Day 24
Data Merging
A data set of gym sessions looks like this:
Each session has the following fields:
- user: User ID of the session's user.
- duration: Duration of the session, in minutes.
- equipment: Array of equipment used during the sessions, in alphabetical order. There are only 5 different equipments.
Implement a method mergeData, which is used to return a unified view of each user's activities by merging data from each user. It has the interface mergeData(sessions). Sessions from the same user should be merged into one object. When merging:
- Sum up the duration fields.
- Combine all the equipment used, de-duplicating the values and sorting alphabetically.
The order of the results should always remain unchanged from the original set, and in the case of merging sessions with the same users, the row should take the place of the earliest occurrence of that user. The input objects should not be modified.
Examples
The following example uses the data set above:
Data of user 7 and user 2 are merged into the first occurrence of that user.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Data Merging
A data set of gym sessions looks like this:
[
{ user: 8, duration: 50, equipment: ['bench'] },
{ user: 7, duration: 150, equipment: ['dumbbell'] },
{ user: 1, duration: 10, equipment: ['barbell'] },
{ user: 7, duration: 100, equipment: ['bike', 'kettlebell'] },
{ user: 7, duration: 200, equipment: ['bike'] },
{ user: 2, duration: 200, equipment: ['treadmill'] },
{ user: 2, duration: 200, equipment: ['bike'] },
];
Each session has the following fields:
- user: User ID of the session's user.
- duration: Duration of the session, in minutes.
- equipment: Array of equipment used during the sessions, in alphabetical order. There are only 5 different equipments.
Implement a method mergeData, which is used to return a unified view of each user's activities by merging data from each user. It has the interface mergeData(sessions). Sessions from the same user should be merged into one object. When merging:
- Sum up the duration fields.
- Combine all the equipment used, de-duplicating the values and sorting alphabetically.
The order of the results should always remain unchanged from the original set, and in the case of merging sessions with the same users, the row should take the place of the earliest occurrence of that user. The input objects should not be modified.
Examples
The following example uses the data set above:
mergeData(sessions);
// [
// { user: 8, duration: 50, equipment: ['bench'] },
// { user: 7, duration: 450, equipment: ['bike', 'dumbbell', 'kettlebell'] },
// { user: 1, duration: 10, equipment: ['barbell'] },
// { user: 2, duration: 400, equipment: ['bike', 'treadmill'] },
// ];
Data of user 7 and user 2 are merged into the first occurrence of that user.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript - Day 25
Event Emitter
In the observer pattern (also commonly known as the publish-subscribe model), we can observe/subscribe to events emitted by publishers and execute code whenever an event happens.
Implement an EventEmitter class similar to the one in Node.js that follows such an observer pattern.
Example usage of the EventEmitter class:
Implement the following APIs:
* new EventEmitter()
Creates an instance of the EventEmitter class. Events and listeners are isolated within the EventEmitter instances they're added to, aka listeners shouldn't react to events emitted by other EventEmitter instances.
* emitter.on(eventName, listener)
Adds a callback function (listener) that will be invoked when an event with the name eventName is emitted.
eventName : string : The name of the event.
listener : Function : The callback function to be invoked when the event occurs.
Returns the EventEmitter instance so that calls can be chained.
* emitter.off(eventName, listener)
Removes the specified listener from the list of listeners for the event with the name eventName.
eventName : string : The name of the event.
listener : Function : Callback function to be removed from the list of listeners for the event.
Returns the EventEmitter instance so that calls can be chained.
* emitter.emit(eventName[, ...args])
Invokes each of the listeners listening to eventName with the supplied arguments in order.
eventName : string : The name of the event.
...args : any : Arguments to invoke the list of listener functions with.
Returns true if the event had listeners, false otherwise.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Event Emitter
In the observer pattern (also commonly known as the publish-subscribe model), we can observe/subscribe to events emitted by publishers and execute code whenever an event happens.
Implement an EventEmitter class similar to the one in Node.js that follows such an observer pattern.
Example usage of the EventEmitter class:
const emitter = new EventEmitter();
function addTwoNumbers(a, b) {
console.log(`The sum is ${a + b}`);
}
emitter.on('foo', addTwoNumbers);
emitter.emit('foo', 2, 5);
// > "The sum is 7"
emitter.on('foo', (a, b) => console.log(`The product is ${a * b}`));
emitter.emit('foo', 4, 5);
// > "The sum is 9"
// > "The product is 20"
emitter.off('foo', addTwoNumbers);
emitter.emit('foo', -3, 9);
// > "The product is -27"
Implement the following APIs:
* new EventEmitter()
Creates an instance of the EventEmitter class. Events and listeners are isolated within the EventEmitter instances they're added to, aka listeners shouldn't react to events emitted by other EventEmitter instances.
* emitter.on(eventName, listener)
Adds a callback function (listener) that will be invoked when an event with the name eventName is emitted.
eventName : string : The name of the event.
listener : Function : The callback function to be invoked when the event occurs.
Returns the EventEmitter instance so that calls can be chained.
* emitter.off(eventName, listener)
Removes the specified listener from the list of listeners for the event with the name eventName.
eventName : string : The name of the event.
listener : Function : Callback function to be removed from the list of listeners for the event.
Returns the EventEmitter instance so that calls can be chained.
* emitter.emit(eventName[, ...args])
Invokes each of the listeners listening to eventName with the supplied arguments in order.
eventName : string : The name of the event.
...args : any : Arguments to invoke the list of listener functions with.
Returns true if the event had listeners, false otherwise.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript - Day 26
Flatten
Implement a function flatten that returns a newly-created array with all sub-array elements concatenated recursively into a single level.
Examples
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Flatten
Implement a function flatten that returns a newly-created array with all sub-array elements concatenated recursively into a single level.
Examples
// Single-level arrays are unaffected.
flatten([1, 2, 3]); // [1, 2, 3]
// Inner arrays are flattened into a single level.
flatten([1, [2, 3]]); // [1, 2, 3]
flatten([
[1, 2],
[3, 4],
]); // [1, 2, 3, 4]
// Flattens recursively.
flatten([1, [2, [3, [4, [5]]]]]); // [1, 2, 3, 4, 5]
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript + HTML - Day 27
getElementsByStyle
Implement a method getElementsByStyle() that finds DOM elements that are rendered by the browser using the specified style. It is similar to Element.getElementsByClassName() but with some differences:
- It is a pure function which takes in an element, a property string, and a value string representing the style's property/value pair to be matched on the elements descendants. E.g. getElementsByStyle(document.body, 'font-size', '12px').
- Similar to Element.getElementsByClassName(), only descendants of the element argument are searched, not the element itself.
- Return an array of Elements, instead of an HTMLCollection of Elements.
Do not use document.querySelectorAll() which will make the problem trivial otherwise. You will not be allowed to use it during real interviews.
Examples
Hint
You might find the Window.getComputedStyle() method helpful.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
getElementsByStyle
Implement a method getElementsByStyle() that finds DOM elements that are rendered by the browser using the specified style. It is similar to Element.getElementsByClassName() but with some differences:
- It is a pure function which takes in an element, a property string, and a value string representing the style's property/value pair to be matched on the elements descendants. E.g. getElementsByStyle(document.body, 'font-size', '12px').
- Similar to Element.getElementsByClassName(), only descendants of the element argument are searched, not the element itself.
- Return an array of Elements, instead of an HTMLCollection of Elements.
Do not use document.querySelectorAll() which will make the problem trivial otherwise. You will not be allowed to use it during real interviews.
Examples
const doc = new DOMParser().parseFromString(
`<div>
<span style="font-size: 12px">Span</span>
<p style="font-size: 12px">Paragraph</p>
<blockquote style="font-size: 14px">Blockquote</blockquote>
</div>`,
'text/html',
);
getElementsByStyle(doc.body, 'font-size', '12px');
// [span, p] <-- This is an array of elements.
Hint
You might find the Window.getComputedStyle() method helpful.
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript + HTML - Day 28
HTML Serializer
Given an object which resembles a DOM tree, implement a function that serializes the object into a formatted string with proper indentation (one tab (\t character) per nesting level) and one tag per line.
Examples
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
HTML Serializer
Given an object which resembles a DOM tree, implement a function that serializes the object into a formatted string with proper indentation (one tab (\t character) per nesting level) and one tag per line.
Examples
const tree = {
tag: 'body',
children: [
{ tag: 'div', children: [{ tag: 'span', children: ['foo', 'bar'] }] },
{ tag: 'div', children: ['baz'] },
],
};
serializeHTML(tree);
// Output:
`<body>
<div>
<span>
foo
bar
</span>
</div>
<div>
baz
</div>
</body>`;
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
Javanoscript - Day 29
JSON.stringify
Implement a function jsonStringify, similar to JSON.stringify that converts a JavaScript value into a JSON string.
- Only JSON-serializable values (i.e. boolean, number, null, array, object) will be present in the input value.
- Ignore the second and the third optional parameters in the original API.
Examples
Other types
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87
JSON.stringify
Implement a function jsonStringify, similar to JSON.stringify that converts a JavaScript value into a JSON string.
- Only JSON-serializable values (i.e. boolean, number, null, array, object) will be present in the input value.
- Ignore the second and the third optional parameters in the original API.
Examples
jsonStringify({ foo: 'bar' }); // '{"foo":"bar"}'
jsonStringify({ foo: 'bar', bar: [1, 2, 3] }); // '{"foo":"bar","bar":[1,2,3]}'
jsonStringify({ foo: true, bar: false }); // '{"foo":true,"bar":false}'
Other types
jsonStringify(null); // 'null'
jsonStringify(true); // 'true'
jsonStringify(false); // 'false'
jsonStringify(1); // '1'
jsonStringify('foo'); // '"foo"'
@danceswithcode
@alithecodeguy
#js #javanoscript #interview87